&引用&引用;。python 3.7中的join()在def中不起作用
我试图用一个函数生成一个唯一的密码。一切正常,除了&引用&引用;。python 3.7中的join()在def中不起作用,python,function,methods,Python,Function,Methods,我试图用一个函数生成一个唯一的密码。一切正常,除了”。加入。帮我看看代码中有什么问题?使用Python3.7 我的代码: import random import string def password(): a = [] letters = string.ascii_letters symbols = string.punctuation for element in range(6): a.append(random.randint(0,
”。加入。帮我看看代码中有什么问题?使用Python3.7
我的代码:
import random
import string
def password():
a = []
letters = string.ascii_letters
symbols = string.punctuation
for element in range(6):
a.append(random.randint(0, 10))
a.append(random.choice(letters))
a.append(random.choice(symbols))
random.shuffle(a)
print(''.join(str(a)))
password()
您使用空字符串作为连接分隔符,它不起任何作用当您在str(a)
上调用join
时,您首先将列表转换为字符串,然后连接字符串化列表中的每个字符
您要做的是将a
中的每个元素转换为字符串。你应该使用一个类似这样的
''.join(str(x) for x in a)
或者,您也可以使用内置函数,当您想要返回一个新的iterable,其中包含应用于iterable
中每个元素的function
结果时,该函数在一般情况下非常有用。因此,您可以使用:
''.join(map(str, a))
这基本上是一个品味的问题,你会发现哪个更具可读性。删除str
,只使用”。加入(a)
不打印密码,返回它。如果没有str
我会得到一个错误,上面写着“预期的str实例,int-found”?和return对没有影响。join()
。我试过了。谢谢你们两个,谢谢你们。两种方法都有效@davedwards现在的回答在[15]中是不正确的,@ice1x,我不明白。对我来说有点陌生python@Jonathan这是一个答案,尽管它是错误的。投反对票,继续前进。另外,请阅读