当前输出:thisisapassword
所需的输出:这是一个密码
answer = urllib.request.urlopen('http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain')
txt = answer.read()
words = txt.splitlines()
password = ''
for c in range(3):
password += random.choice(words)
print(password)
答案 0 :(得分:0)
您可以做两件事:
当您附加每个新单词时,也要附加连字符。循环结束后,使用password = password[:-1]
删除尾随连字符:
password = ''
for c in range(3):
password += random.choice(words)
password += '-'
password = password[:-1]
print(password)
另一方面,您可以将所有三个单词存储为列表,然后使用.join
添加连字符并转换为字符串。例如:
password = []
for c in range(3):
password.append(random.choice(words))
print('-'.join(password))
如果你想把它压缩成一个oneliner,那么你有以下列表理解,正如@JonClements所指出的那样:
password = '-'join(random.choice(words) for _ in range(3))
或者在Python 3.6中:
password = '-'join(random.choices(words, k=3))