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('allnum和allalpha不能同时为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