.join()方法到底做什么? [英] What exactly does the .join() method do?
问题描述
我刚接触Python,对.join()
完全感到困惑,我读过的.join()
是连接字符串的首选方法.
I'm pretty new to Python and am completely confused by .join()
which I have read is the preferred method for concatenating strings.
我尝试过:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
有类似的东西:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
为什么这样工作? 595
不应该被自动添加吗?
Why does it work like this? Shouldn't the 595
just be automatically appended?
推荐答案
仔细查看您的输出:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^
我突出显示了原始字符串的"5","9","5". Python join()
方法是字符串方法,它采用与字符串连接的事物的 list .一个更简单的示例可能有助于解释:
I've highlighted the "5", "9", "5" of your original string. The Python join()
method is a string method, and takes a list of things to join with the string. A simpler example might help explain:
>>> ",".join(["a", "b", "c"])
'a,b,c'
在给定列表的每个元素之间插入,".在您的情况下,您的列表"是字符串表示形式"595",它被视为列表["5","9","5"].
The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].
您似乎正在寻找+
,而不是:
It appears that you're looking for +
instead:
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
这篇关于.join()方法到底做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!