Python 生成给定长度的随机字符串
pythonserver side programmingprogramming更新于 2025/7/31 8:44:17
在本文中,我们将了解如何生成具有给定长度的随机字符串。这对于创建随机密码或其他需要随机性的程序很有用。
使用 random.choices
random 模块中的 choice 函数可以生成字符串,然后可以将其连接起来以创建给定长度的字符串。
示例
import string
import random
# 所需字符串的长度
N = 5
# 使用 random.choices()
res = ''.join(random.choices(string.ascii_letters+
string.digits, k=N))
# 结果
print("Random string : ",res)
输出
运行上述代码得到以下结果 −
Random string : nw1r8
使用secrets
secrets 模块也有 choice 方法,可用于生成随机字符串。但在这里我们可以从字符串模块输入不同的条件,例如仅小写字母和所有数字。
示例
import string
import secrets
# 所需字符串的长度
N = 5
# 使用 random.choices()
res = ''.join(secrets.choice(string.ascii_lowercase + string.digits)
for i in range(N))
# 结果
print("Random string : ",res)
输出
运行上述代码得到以下结果 −
Random string : p4ylm
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

