Q:

Python program for adding given string with a fixed message

belongs to collection: Python String Programs

0

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

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 " ".

Example:

    print('Hello World') 
    #or
    print("Hello World") 

This would display Hello World as an output.

Now starting with our question,

Question:

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'

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Find all permutations of a given string in Python... >>
<< Python program to remove a character from a specif...