You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
738 B
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import random
import string
def generate_random_string(length=16):
"""
生成指定长度的随机字符串,不包含短横线(-)
参数:
length: 字符串长度默认16
返回:
随机字符串
"""
# 定义可用字符集:字母(大小写) + 数字
characters = string.ascii_letters + string.digits
# 随机选择字符并拼接
random_str = ''.join(random.choice(characters) for _ in range(length))
return random_str
# 示例用法
if __name__ == "__main__":
# 生成16位随机字符串
print(generate_random_string())
# 生成32位随机字符串
print(generate_random_string(32))
# 生成8位随机字符串
print(generate_random_string(8))