import random点击查看代码
import string
def generate_str_num_code(length):
characters=string.digits+string.ascii_letters #type--><class 'str'>
code=""
for i in range(length):
code=code+ random.choice(characters)
#code = code + str(random.sample(characters,1))
#print(type(str(random.sample(characters,1)))) #class 'str'> ['2']
# type--><class 'str'> random.sample(characters,1)的结果是一个list,即使用str强制转换,看起来也还有列表的特征['w']['E']['o']['8'],而random.choice(characters)是单个的字符
return code
ret = generate_str_num_code(4) #type--><class 'str'>
print(ret)
print(f"the code you generated is: {ret}")
以下是辅助理解代码用:
import random
characters='0123456789'
print(random.choice(characters)) # 9
print(type(random.choice(characters))) # <class 'str'>
print(random.sample(characters,1)) # ['9']
print(type(random.sample(characters,1))) # <class 'list'>
list=[['a'],['b'],'c']
list1 = [1,2,3]
print(str(list)) # [['a'], ['b'], 'c']
print(str(list1)) # [1, 2, 3]