-5

我在python中有一个字符串

 name="My name is John"

我想将名称替换为:

 name ="My name is JohnSmith"

谁能帮忙??

4

3 回答 3

2

你不能在 python 中修改一个字符串,因为它们是不可变的,所以修改一个字符串总是会产生一个新的字符串。

对于您的示例,您可以使用:

字符串连接:

>>> name = "My name is John"
>>> name += "Smith"       #equivalent to name = name + "Smith"
>>> name
'My name is JohnSmith'

或字符串格式:

>>> name = "My name is John"
>>> name = "{0}{1}".format(name,"Smith")
>>> name
'My name is JohnSmith'

对于连接许多项目的列表,首选str.join

>>> name="My name is John"
>>> name = "".join((name,"Smith","foo","bar","spam"))
>>> name
'My name is JohnSmithfoobarspam'
于 2013-05-07T13:36:19.357 回答
0
>>> name[:11] + 'John Smith'
'My name is John Smith'
于 2013-05-07T13:38:47.320 回答
-1
str = "My name is John"
str = str.replace("John","JohnSmith")
于 2013-05-07T13:40:14.343 回答