gpt4 book ai didi

python - 如何以最佳方式将字符列表连接到字符串?

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

数据:

list = ['a','b','x','d','s']

我想创建一个字符串 str = "abxds"。我该怎么做?

现在我正在做类似的事情:

str = ""
for i in list:
str = str + i
print(str)

我知道字符串在 Python 中是不可变的,这将创建 7 个字符串对象。当我重复数千次时,我的内存就消失了。

有没有更有效的方法?

最佳答案

>>> theListOfChars = ['a', 'b', 'x', 'd', 's']
>>> ''.join(theListOfChars)
'abxds'

顺便说一句,不要使用 liststr 作为变量名,因为它们已经是内置函数的名称。

(此外,Python 中没有 char。“字符”只是一个长度为 1 的字符串。因此 ''.join 方法适用于列表字符串也是如此。)

关于python - 如何以最佳方式将字符列表连接到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166641/

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