为什么内置连接对我的代码没有影响?

编程入门 行业动态 更新时间:2024-10-13 22:24:38
本文介绍了为什么内置连接对我的代码没有影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个错误,我减少到这个:

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 >>>

更多推荐

为什么内置连接对我的代码没有影响?

本文发布于:2023-10-27 10:51:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533155.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!