为什么内置的联接对我的代码没有影响? [英] Why is the join built-in having no influence on my code?
本文介绍了为什么内置的联接对我的代码没有影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个错误可以归结为:
I had a bug that I reduced down to this:
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
does not operate in-place because string objects are immutable in Python. Instead, it returns an entirely new string object.
如果要a
引用此新对象,则需要显式重新分配它:
If you want a
to reference this new object, you need to explicitly reassign it:
a = " ".join(a)
演示:
>>> a = ['a','b','c']
>>> print "Before", a
Before ['a', 'b', 'c']
>>> a = " ".join(a)
>>> print "After", a
After a b c
>>>
这篇关于为什么内置的联接对我的代码没有影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文