省略某个字符在随机密码生成器程序中输出

问题描述 投票:0回答:2

我正在编写一个随机生成任意数量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>代表什么?
  • 在程序的一些迭代期间,打印出这些字符代码。
  • 它们代表白色空间吗?
  • random_pass()函数中的if语句不会忽略出现在输出中的字符代码。这就是我现在寻求帮助的原因。
python random module character ascii
2个回答
0
投票

根据common strings operations上的Python文档:

string.printable

被认为是可打印的字符串。这是数字,字母,标点符号和空格的组合。

和空格定义为:

string.whitespace

包含所有被视为空格的字符的字符串。在大多数系统中,这包括字符空间,制表符,换行符,返回页,换页符和垂直选项卡。

因此,有时在random.choice(x)中有这些角色是正常的

  • 0x0c是换行符
  • 0x0b是垂直选项卡

你可能不应该使用string.printable,而是使用像string.ascii_letters + string.digits + string.punctuation这样的东西


0
投票

<0x0c>和<0x0b>代表什么?

在程序的一些迭代期间,打印出这些字符代码。

  • 0x0c是换行
  • 0x0b是垂直标签

你可以在ASCII table中查找它们

它们代表白色空间吗?

是的,他们是string.whitespace的一部分

random_pass()函数中的if语句不会忽略出现在输出中的字符代码。这就是我现在寻求帮助的原因。

检查0x0c0x0b的条件从未执行,因为它是在returnrandom_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
© www.soinside.com 2019 - 2024. All rights reserved.