[英]Python: How to import ascii characters
For the password entry field of an email client that I am making, I thought that it would be cool to have the password show random characters. 对于我正在制作的电子邮件客户端的密码输入字段,我认为让密码显示随机字符会很酷。 Since I don't want to write down a dictionary of all ascii characters, I was wondering if there is a module which I could import to get it. 因为我不想写下来的所有ASCII字符的字典,我在想,如果有,我可以导入得到它的模块。 My idea of the code looks like this: 我对代码的想法如下所示:
import random
import char_set #All ascii characters
def random_char():
char_select = random.randrange(len(char_set))
char_choice = char_set[char_select]
return char_choice
NOTE: This must be cross-platform as I run on Mac OSX, Windows, and Debian (Raspberry Pi). 注意:这必须是跨平台的,因为我在Mac OSX,Windows和Debian(Raspberry Pi)上运行。
The whole ASCII set: 整个ASCII集:
In [22]: "".join(chr(x) for x in range(128))
Out[22]: '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'
If you want the printable ascii characters: 如果需要可打印的ASCII字符:
In [9]: "".join(chr(x) for x in range(32,127))
Out[9]: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
or if you only want the alphabets: 或者,如果您只想要字母:
In [10]: import string
In [11]: string.ascii_letters
Out[11]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.printable
is also an option, it contains 5 extra charcters that are not in the range(32,127): string.printable
也是一个选项,它包含5个不在范围(32,127)中的额外字符:
In [39]: s1=set(x for x in string.printable)
In [40]: s2=set(chr(x) for x in range(32,127))
In [41]: s1-s2
Out[41]: set(['\t', '\x0b', '\n', '\r', '\x0c'])
The string
module includes a number of constants you can use: string.letters
, string.numbers
, string.punctuation
, etc. string.printable
seems to be largely what you want. string
模块包含许多可以使用的常量: string.letters
, string.numbers
, string.punctuation
等string.printable
似乎是您想要的。
If you don't want to use a module, just do printable_chars = "".join(chr(c) for c in xrange(33, 127))
(this excludes space and rubout intentionally). 如果您不想使用模块,只需执行printable_chars = "".join(chr(c) for c in xrange(33, 127))
(这有意排除了空间和外表)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.