gpt4 book ai didi

python - .join() 方法到底是做什么的?

转载 作者:IT老高 更新时间:2023-10-28 12:16:39 26 4
gpt4 key购买 nike

我对 Python 还是很陌生,完全被我读过的 .join() 弄糊涂了,这是连接字符串的首选方法。

我试过了:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)

得到类似的东西:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5

为什么会这样? 595 不应该只是自动附加吗?

最佳答案

仔细查看您的输出:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^

我已突出显示原始字符串的“5”、“9”、“5”。 python join() method 是一个字符串方法,它需要一个 list 的东西来加入字符串。一个更简单的例子可能有助于解释:

>>> ",".join(["a", "b", "c"])
'a,b,c'

“,”插入给定列表的每个元素之间。在您的情况下,您的“列表”是字符串表示“595”,它被视为列表 [“5”、“9”、“5”]。

您似乎正在寻找 +:

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid

关于python - .join() 方法到底是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1876191/

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