我正在尝试更新一个生成字符串的脚本,以便它可以在Python 3上运行。这是麻烦的代码段:
from itertools import islice, repeat
from os import urandom
import string
string_len = 16
chars = string.ascii_letters + string.digits + string.punctuation
char_gen = (c for c in map(urandom, repeat(1)) if c in chars)
pswd_text = ''.join(islice(char_gen, None, string_len))
但不幸的是,我收到一个TypeError:
% python3 ./string_generator.py
Traceback (most recent call last):
File "./string_generator.py", line 12, in <module>
pswd_text = ''.join(islice(char_gen, None, pswd_len))
File "./string_generator.py", line 10, in <genexpr>
c for c in map(urandom, repeat(1)) if c in chars
TypeError: 'in <string>' requires string as left operand, not bytes
我很确定这是导致TypeError的map函数的迭代,但是我还无法弄清楚如何将其转换为字符串或其他任何解决方案。非常感谢您的帮助或想法。
问题在于混合bytes
和str
价值观。确保所有内容都以字节为单位使其可以工作,因为urandom
返回字节。
# Encode the concatenated strings into a byte string
chars = (string.ascii_letters + string.digits + string.punctuation).encode()
char_gen = (c for c in map(urandom, repeat(1)) if c in chars)
# Use an empty byte string to join the generated bytes
pswd_text = b''.join(islice(char_gen, None, string_len))
您随时可以调用pswd_text.decode()
以获取unicode字符串(str
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句