Python program for adding given string with a fixed message

Here, we are going to learn how to add a given string with a fixed message/string using python program? By Suryaveer Singh Last updated : February 25, 2024

Here in this tutorial, we would learn how to use strings in Python? We would code here to add different strings together. Initially, we should know what a string is so, a String in python is surrounded by single quotes or a double quotes i.e. ' ' or " ".

Problem statement

Given a string and we have to add a greeting message like Hello with the string and return it using python program.

We are given with string of some peoples name and all we got to do is to add "Hello" before their names in order to greet them. If the string already begins with "Hello", then return the string unchanged.

Example

greeting('Santosh') = 'Hello Santosh'
greeting('Ram') = 'Hello Ram'
greeting('Hello Shyam') = 'Hello Shyam'

Solution

Now this problem is a bit complex as we have to check whether "Hello" is attached initially or not!

We can solve this problem by just adding an if statement.

Code

def greeting(str):
    if len(str) >= 5 and str[:5] == 'Hello':
        return str
    return 'Hello ' + str

print (greeting('Prem'))
print (greeting('David'))
print (greeting('Hello Watson!'))

Output

Hello Prem
Hello David
Hello Watson!

In the last line of our code while typing string Hello we have provided space so that Hello and the name do not join together and look ugly.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.