在python中修改字符串

时间:2013-05-07 13:35:30

标签: python

我在python中有一个字符串

 name="My name is John"

我想用以下名称替换姓名:

 name ="My name is JohnSmith"

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

>>> name[:11] + 'John Smith'
'My name is John Smith'

答案 2 :(得分:-1)

str = "My name is John"
str = str.replace("John","JohnSmith")