Cha*_*ton 3 python string join
我有一个错误,我减少到这个:
a = ['a','b','c']
print( "Before", a )
" ".join(a)
print( "After", a )
Run Code Online (Sandbox Code Playgroud)
哪个输出:
runfile('C:/program.py', wdir=r'C:/')
Before ['a', 'b', 'c']
After ['a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
iCo*_*dez 12
str.join因为字符串对象在Python中是不可变的,所以不会就地操作.相反,它返回一个全新的字符串对象.
如果要a引用此新对象,则需要显式重新分配:
a = " ".join(a)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> a = ['a','b','c']
>>> print "Before", a
Before ['a', 'b', 'c']
>>> a = " ".join(a)
>>> print "After", a
After a b c
>>>
Run Code Online (Sandbox Code Playgroud)