带有固定消息的给定字符串添加的Python程序

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

给定一个字符串,我们必须在该字符串中添加问候消息(如Hello),然后使用python程序将其返回。

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

在本教程的此处,我们将学习如何在Python中使用字符串? 我们将在此处进行编码以将不同的字符串添加在一起。 最初,我们应该知道字符串是什么,python中的字符串被单引号或双引号包围,即''或“” 。

Example:

例:

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

This would display Hello World as an output.

这会将Hello World显示为输出。

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.

我们得到了一些人的名字的字符串,我们要做的就是在他们的名字前添加“ Hello” ,以问候他们。 如果字符串已经以“ Hello”开头,则返回原样的字符串。

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!

现在这个问题有点复杂了,因为我们必须检查最初是否附加了“ Hello”

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

我们可以通过添加if语句来解决此问题。

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.

在代码的最后一行中,输入字符串Hello时,我们提供了空格,以使Hello和名称不会连接在一起并且看起来很丑。

翻译自: https://www.includehelp.com/python/program-for-adding-given-string-with-a-fixed-message.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值