import random
import string
def generate_random_string(length):
# 定义包含特殊字符、数字和字母的字符集
special_chars = string.punctuation
digits = string.digits
letters = string.ascii_letters
# 确保每个字符集的长度为总长度的三分之一
special_chars_len = length // 3
digits_len = length // 3
letters_len = length - special_chars_len - digits_len
# 生成随机字符串
random_string = (
''.join(random.choice(special_chars) for _ in range(special_chars_len)) +
''.join(random.choice(digits) for _ in range(digits_len)) +
''.join(random.choice(letters) for _ in range(letters_len))
)
# 将字符串打乱顺序
random_string = ''.join(random.sample(random_string, len(random_string)))
return random_string
# 生成包含特殊字符、数字和字母的长度为 12 的随机字符串
random_str = generate_random_string(12)
print(random_str)
执行结果
Oli54}`27@~X
]B8_9w|60'YY
5;Skd<K9!5\2
7#"gm4L.V5@9
(KH/C?32l2;8
7J$2|I8"9f{l
&(9>y0l4X)4p
a{[9~Cyq$009
s}`lY696y"1"
h430:6UO_J"&
^t&4v#j34!z4
^[5y8*0e9q)S