N = 6 result = ''.join(random.choices(string.ascii_uppercase + string.digits, k=N)) print(result)
PYTHON
3. 安全版本:使用 random.SystemRandom()
1 2 3 4 5 6
import string import random
N = 6 result = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ inrange(N)) print(result)
PYTHON
4. 使用 secrets 模块(Python 3.6+)
1 2 3 4 5 6 7
import string import secrets
N = 6 alphabet = string.ascii_uppercase + string.digits password = ''.join(secrets.choice(alphabet) for i inrange(N)) print(password)
PYTHON
5. 使用 uuid 模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import uuid
# 单行实现 result = uuid.uuid4().hex.upper()[0:6] print(result)
# 封装成函数 defmy_random_string(string_length=10): random = str(uuid.uuid4()) random = random.upper() random = random.replace("-", "") return random[0:string_length]
print(my_random_string(6))
PYTHON
6. 使用 strgen 模块
1 2 3 4 5 6 7 8 9 10 11 12 13
from strgen import StringGenerator as SG
# 生成6字符随机字符串 result = SG("[\u\d]{6}").render() print(result)