在Python上获得随机字符

"""今天写一个程序,在想既然可以获得随机数,那我可不可以获得任意字符呢,于是在stackoverflow.com 上找到了方法,几乎都是用导入random,然后再用其它方法间接实现随机字符。
现在总结如下:"""

#获取单个
>>> import random
>>> import string   
>>> random.choice(string.ascii_lowercase)
'b'

>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.letters)
'j'


import random
def guess_letter():
    return random.choice('abcdefghijklmnopqrstuvwxyz')

import string #This was a design above but failed to print. I remodled it.
import random
irandom = random.choice(string.ascii_letters)
print irandom

#获取一串:

>>>def random_char(y):
      return ''.join(random.choice(string.ascii_letters) for x in range(y))

>>>print (random_char(5))
>>>fxkea

可以简化为:''.join(random.sample(string.ascii_lowercase,5))

import string
import random

KEY_LEN = 20

def base_str():
    return (string.letters+string.digits) 
def key_gen():
    keylist = [random.choice(base_str()) for i in range(KEY_LEN)]
    return ("".join(keylist))
You can get random strings like this:

g9CtUljUWD9wtk1z07iF
ndPbI1DDn6UvHSQoDMtd
klMFY3pTYNVWsNJ6cs34
Qgr7OEalfhXllcFDGh2l

相关推荐