Home » Python » Python programs

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?
Submitted by Suryaveer Singh, on June 08, 2019

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'

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.