其他分享
首页 > 其他分享> > 2018-04-03-2-生成随机字符串

2018-04-03-2-生成随机字符串

作者:互联网

生成随机字符串

一个是uuid 为了获取一个随机字符串

另一个是md5摘要 用来获得固定长度的字符串

>>> import uuid
>>> import hashlib
>>> def get_filename():
	#获取随机的uuid类型的字符串
	my_uuid = uuid.uuid4()
	
	print(my_uuid)
	
	#把uuid转成str
	uuid_str = str(my_uuid).encode("utf-8")
	print(uuid_str)
	
	# 获得md5对象
	md5 = hashlib.md5()
	print(md5)
	
	#将我们需要做摘要的字符串 进行md5摘要
	md5.update(uuid_str)
	
	#获取32固定长度的结果
	return md5.hexdigest()

>>> get_filename()
5929c6e7-ee56-4a98-8bf6-b29b3acd860b
b'5929c6e7-ee56-4a98-8bf6-b29b3acd860b'
<md5 HASH object @ 0x0000000002DD0AD0>
'c09baa36821283d0b0a70668529cace9'
>>> ss ='c09baa36821283d0b0a70668529cace9'
>>> len(ss)
32

printable

#在python中, string.printable :包含所有可打印字符的字符串。
>>> from string import printable
>>> printable[:62]
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

choice

Python choice() 函数
choice(seq) 方法返回一个列表,元组或字符串的随机项
choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.

>>> from random import choice
>>> choice(printable[:62])
'7'
>>> choice(printable[:62])
'z'
>>> choice(printable[:62])
'9'
>>> [choice(printable[:62]) for i in range(4)]
['9', 's', 'I', 'j']
>>> [choice(printable[:62]) for i in range(4)]
['T', 'h', '1', 'D']
>>> [choice(printable[:62]) for i in range(4)]
['p', 'y', 'h', 'h']

生成4位的email_code

>>> from string import printable
>>> from random import choice
>>> email_code = ''.join([choice(printable[:62]) for i in range(4)])
>>> email_code
'p7YB'

标签:03,uuid,04,printable,choice,62,2018,import,md5
来源: https://blog.csdn.net/github_38970218/article/details/88771363