为什么内置连接对我的代码没有影响? [英] Why is the join built-in having no influence on my code?
本文介绍了为什么内置连接对我的代码没有影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个错误,我减少到这个:
a = ['a','b','c']打印(之前",一个)" ".join(a)打印(之后",一个)
输出这个:
runfile('C:/program.py', wdir=r'C:/')在 ['a', 'b', 'c'] 之前['a', 'b', 'c'] 之后
这是怎么回事?
解决方案
str.join
不能就地操作,因为字符串对象在 Python 中是不可变的.相反,它返回一个全新的字符串对象.
如果你想让 a
引用这个新对象,你需要显式地重新赋值:
a = " ".join(a)
演示:
<预><代码>>>>a = ['a','b','c']>>>打印之前",一个在 ['a', 'b', 'c'] 之前>>>a = " ".join(a)>>>打印之后",一个在 a b c 之后>>>I had a bug that I reduced down to this:
a = ['a','b','c']
print( "Before", a )
" ".join(a)
print( "After", a )
Which outputs this:
runfile('C:/program.py', wdir=r'C:/')
Before ['a', 'b', 'c']
After ['a', 'b', 'c']
What's going on here?
解决方案
str.join
does not operate in-place because string objects are immutable in Python. Instead, it returns an entirely new string object.
If you want a
to reference this new object, you need to explicitly reassign it:
a = " ".join(a)
Demo:
>>> a = ['a','b','c']
>>> print "Before", a
Before ['a', 'b', 'c']
>>> a = " ".join(a)
>>> print "After", a
After a b c
>>>
这篇关于为什么内置连接对我的代码没有影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文