我正在编写一个随机生成任意数量ASCII字符组合的程序。
import random
import string
string.printable
sP = string.printable
def random_pass(stringLength):
x = sP
return ''.join((random.choice(x)) for i in range(stringLength))
if x == '<0x0c>' or '<0x0b>:
print("Try again!")
print('You'\re password is: ', random_pass(12))
<0x0c>
和<0x0b>
代表什么?根据common strings operations上的Python文档:
string.printable
被认为是可打印的字符串。这是数字,字母,标点符号和空格的组合。
和空格定义为:
string.whitespace
包含所有被视为空格的字符的字符串。在大多数系统中,这包括字符空间,制表符,换行符,返回页,换页符和垂直选项卡。
因此,有时在random.choice(x)
中有这些角色是正常的
你可能不应该使用string.printable
,而是使用像string.ascii_letters + string.digits + string.punctuation
这样的东西
<0x0c>和<0x0b>代表什么?
在程序的一些迭代期间,打印出这些字符代码。
0x0c
是换行0x0b
是垂直标签你可以在ASCII table中查找它们
它们代表白色空间吗?
是的,他们是string.whitespace
的一部分
random_pass()函数中的if语句不会忽略出现在输出中的字符代码。这就是我现在寻求帮助的原因。
检查0x0c
和0x0b
的条件从未执行,因为它是在return
的random_pass
声明之后。
正如@ Tigre-Bleu已经建议你应该使用string.ascii_letters + string.digits + string.punctuation
而不是string.printable
此外,您应该在生成密码时使用加密强大的随机数生成器。如果你使用Python> = 3.6,你可以使用secrets
模块:
import secrets
import string
def random_pass(stringLength):
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for i in range(stringLength))
return password
print('Your password is:', random_pass(12))
# Your password is: 2;=1!*A.dK;+
对于Python <3.6你可以使用random.SystemRandom()
,它将在支持它的系统上使用os.urandom()
:
import random
import string
def random_pass(stringLength):
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.SystemRandom().choice(alphabet) for i in range(stringLength))
return password
print 'Your password is:', random_pass(12)
# Your password is: V9I:+H{_>*'p