我在python中有一个字符串
name="My name is John"
我想将名称替换为:
name ="My name is JohnSmith"
谁能帮忙??
你不能在 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'
>>> name[:11] + 'John Smith'
'My name is John Smith'
str = "My name is John"
str = str.replace("John","JohnSmith")