在 Python 中生成特定长度的随机字符串的最佳方法是什么? [英] What's the best way to generate random strings of a specific length in Python?

查看:22
本文介绍了在 Python 中生成特定长度的随机字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个项目,我需要一种创建数千个随机字符串同时保持低冲突的方法.我正在寻找它们只有 12 个字符长和大写.有什么建议吗?

For a project, I need a method of creating thousands of random strings while keeping collisions low. I'm looking for them to be only 12 characters long and uppercase only. Any suggestions?

推荐答案

CODE:

from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))

输出:

5 个例子:

QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD

<小时>

如果您只需要数字,请使用 digits 常量而不是 ascii_uppercase 来自 string 模块的一个.

If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.

3 个例子:

229945986931
867348810313
618228923380

这篇关于在 Python 中生成特定长度的随机字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆