python 生成随机字符串


import string
import time
import random

def create_name(prefix="", length=8, allnum=False, allalpha=False, time_subfix=False, onlylow=True):
"""
创建随机字符串,仅包含大小写字母、数字
:param prefix: 前缀,默认无
:param length: 字符串长度
:return: 返回创建的字符串
"""
prefix_len = 0
if prefix:
prefix_len = len(prefix)
try:
assert prefix_len < length
except:
return prefix
name_len = length - prefix_len
temp_str = string.ascii_letters
temp_num = string.digits
if allnum and allalpha:
raise ValueError(‘allnumallalpha不能同时为True‘)
elif allnum:
new_name = prefix + ‘‘.join([random.choice(temp_num) for i in range(name_len)])
elif allalpha:
new_name = prefix + ‘‘.join([random.choice(temp_str) for i in range(name_len)])
else:
new_name = prefix + "".join([random.choice(temp_str + temp_num) for i in range(name_len)])
if time_subfix:
new_name += str(int(time.time()))
print("create new name: %s" % new_name)
if onlylow:
new_name = new_name.lower()
return new_name

python 生成随机字符串

上一篇:python 实现AES CBC 与PKCS7Padding联合加密


下一篇:Python xlwings 更新表格sheet