在Python中可以结合string和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
下面这个例子是实现随机字符的完整代码,包括大小字母、数字、特殊字符。构造的方法与上述一致:
import random
import string
import sys
#存储大小写字母和数字,特殊字符列表
STR = [chr(i) for i in range(65,91)] #65-91对应字符A-Z
str = [chr(i) for i in range(97,123)] #a-z
number = [chr(i) for i in range(48,58)] #0-9
#特殊字符串列表获取有点不同
initspecial = string.punctuation #这个函数获取到全部特殊字符,结果为字符串形式
special = [] #定义一个空列表
#制作特殊符号列表
for i in initspecial:
special.append(i)
total = STR + str + number + special
#print total
choices = ['6','8','10','16']
def Randompassword(your_choice):
if your_choice in choices:
passwordli = random.sample(total,int(your_choice)) ##sample函数作用是取几个列表里的值并返回一个新列表,此处得到的是列表需要转换为字符串显示出来
passwordst = ''.join(passwordli) #现在得到的是转换后的字符串 ‘’是分隔符,里面可以为; : . 等等
print "\033[32m生成的\033[0m" + your_choice + "\033[32m位数密码为:\033[0m\n" + passwordst
else:
print "\033[31m请输入指定位数(6,8,10,16) \033[0m"
if __name__ == '__main__':
while True:
choice = raw_input("\033[33m请输入你要得到随机密码的位数:(6,8,10,16)\033[0m\n")
if choice != 'q': #输入q则退出循环
Randompassword(choice) #执行函数
else:
break
参考文献:
1、https://www.cnblogs.com/longsecond/p/6118943.html 2018.4.27
2、https://www.cnblogs.com/misswangxing/p/7834157.html 2018.4.27
3、http://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python 2018.4.27