gpt4 book ai didi

python - 为什么 join 内置函数对我的代码没有影响?

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:52 24 4
gpt4 key购买 nike

我有一个错误,我将其简化为:

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 中是不可变的。相反,它返回一个全新的字符串对象。

如果你想让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
>>>

关于python - 为什么 join 内置函数对我的代码没有影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com