Python生成随机字符串

 
import string
import random
 
def get_random_code(length=6, allow_symbol=False): 
    """
    随机生成N位字符串
    length: 字符串长度
    allow_symbol: 生成的字符串中是否包含符号,默认只包含数字和字母
    """
    chars = string.printable if allow_symbol else string.ascii_letters + string.digits
    return ''.join(random.sample(chars, length))
 
get_random_code()
 
 
==================================
 
说明:
 
>>> import string
 
>>> string.digits

'0123456789'

 

>>> string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

 

>>> string.printable

'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

 
-------------------------
 
random.sample(chars, length):从chars字符串中随机选取length位做一个切片返回(不会有重复字符)
 
 
参考文档:
 
posted @ 2018-11-02 13:52  朔雪寒D.A.G  阅读(410)  评论(0编辑  收藏  举报