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

我是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()方法是一个字符串方法,它接收一个*列表,将其与字符串连接。一个更简单的例子可能有助于解释。

>>> ",".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
评论(4)

join需要一个可迭代的东西作为参数。 通常是一个列表。 在你的例子中,问题在于字符串本身是可迭代的,依次给出每个字符。你的代码是这样分解的。

"wlfgALGbXOahekxSs".join("595")

其作用与此相同。

"wlfgALGbXOahekxSs".join(["5", "9", "5"])

从而产生你的字符串。

"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"

作为迭代变量的字符串是Python中最令人困惑的起始问题之一。

评论(1)

join()是用来连接所有列表元素的。对于连接两个字符串来说,"+"会更有意义。

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