如何在 Python 中创建随机字符串?
我需要它是数字然后是字符,重复直到迭代完成。
这是我创建的:
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id += random.choice(alpha)
return id
最佳答案
从(例如)小写字符生成字符串:
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
结果:
>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'
https://stackoverflow.com/questions/2030053/