2013-05-07 49 views
-4

字符串我有蟒蛇修改蟒蛇

name="My name is John" 

我要替换名称的字符串:

name ="My name is JohnSmith" 

谁能帮助?

+1

请注意,您不能在Python中修改字符串,字符串是不可变的。你可以将'name'绑定到一个*完全不同的*字符串,这个新的字符串具有你想要的内容。 – 2013-05-07 13:37:44

+1

如果你想用不同的字符串替换名字,你已经在你的例子中这样做了。 :) – dansalmo 2013-05-07 14:50:48

回答

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' 
+0

你应该改写它,“为了连接多个项目列表”,比较喜欢'str.join',对于2个项目,'“”.join((x,y))'只是一个丑陋的版本'x + y' – jamylak 2013-05-07 13:48:07

0
>>> name[:11] + 'John Smith' 
'My name is John Smith' 
-1
str = "My name is John" 
str = str.replace("John","JohnSmith") 
+3

不要调用你的字符串'str','str'是一个内建的 – jamylak 2013-05-07 13:40:49

+0

是的,我不应该这样做。 – manoj 2013-05-07 13:42:31

+2

现在尝试'print str(1)' – jamylak 2013-05-07 13:43:43