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