标签:one bcd att form zab 随机 hit 之间 字母
random随机包
>>> import random #导入随机包
#取随机整数 >>> random.randint(1,10) 4
#取夸指定步长的随机整数 >>> random.randrange(1,10,2) #随机取1-10之间的奇数 9 >>> random.randrange(0,10,2) 2
#去0-1之间的随机小数 >>> random.random() 0.25631948996842346 #取指定区间的随机小数 >>> random.uniform(1,10) 3.1196351125028334 >>> random.uniform(1,10) 5.857263369842762 >>>
#随机取一个字符 >>> random.choice(‘abcdefg‘) ‘f‘ #随机取指定个数字符 >>> random.sample(‘abcdefg‘,3) [‘f‘, ‘d‘, ‘e‘]
#随机打乱排序,只能针对列表;原地乱序:改变原列表的顺序,且不返回值,返回的是None >>> s=[1,2,3,4,5] >>> random.shuffle(s) >>> s [3, 4, 1, 2, 5]
#生成随机的十个小写字母
>>> result =""
>>> for i in range(10):
... result +=chr(97+random.randint(1,25))
...
>>> print(result)
iiixvsfltw
#生成随机不限定大小写个数的10个字母
>>> result=""
>>> lower_case_letter_num = random.randint(1,9)
>>> upper_case_letter_num = 10-lower_case_letter_num
>>> for i in range(lower_case_letter_num):
... result +=chr(ord("a")+random.randint(1,25))
...
>>> for i in range(upper_case_letter_num):
... result +=chr(ord("A")+random.randint(1,25))
...
>>> print(result)
ypskdkIDTN
string包
>>> import string #导入string包 >>> dir(string) #查看该包里有哪些方法 [‘Formatter‘, ‘Template‘, ‘_ChainMap‘, ‘_TemplateMetaclass‘, ‘__all__‘, ‘__built ins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__packag e__‘, ‘__spec__‘, ‘_re‘, ‘_string‘, ‘ascii_letters‘, ‘ascii_lowercase‘, ‘ascii_u ppercase‘, ‘capwords‘, ‘digits‘, ‘hexdigits‘, ‘octdigits‘, ‘printable‘, ‘punctua tion‘, ‘whitespace‘] >>> string.ascii_letters #获取所有的字母(包括大写和小写) ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘ >>> string.ascii_lowercase #获取所有小写字母 ‘abcdefghijklmnopqrstuvwxyz‘ >>> string.ascii_uppercase #获取所有大写字母 ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘ >>> string.digits #获取所有数字 ‘0123456789‘
练习:
# 从a-zA-Z0-9生成指定数量的随机字符: >>> string.ascii_letters ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘ >>> string.digits ‘0123456789‘ >>> random.sample(string.ascii_letters+string.digits,8) [‘n‘, ‘q‘, ‘f‘, ‘7‘, ‘L‘, ‘p‘, ‘I‘, ‘y‘] >>> ‘‘.join(random.sample(string.ascii_letters+string.digits,8)) ‘GgHXmqbj‘ >>> ‘‘.join(random.sample(string.ascii_letters+string.digits,8)) ‘XFCf2KvQ‘
标签:one bcd att form zab 随机 hit 之间 字母
原文地址:https://www.cnblogs.com/wenm1128/p/11558074.html