我有一个错误,我将其简化为:
a = ['a','b','c'] print( "Before", a ) " ".join(a) print( "After", a )
输出以下内容:
runfile('C:/program.py', wdir=r'C:/') Before ['a', 'b', 'c'] After ['a', 'b', 'c']
这里发生了什么?
str.join不能就地操作,因为字符串对象在Python中是不可变的。而是返回一个全新的字符串对象。
str.join
如果要a引用此新对象,则需要显式重新分配它:
a
a = " ".join(a)
演示:
>>> a = ['a','b','c'] >>> print "Before", a Before ['a', 'b', 'c'] >>> a = " ".join(a) >>> print "After", a After a b c >>>