在本教程中,我们将研究在 Python 中生成随机字符串的各种技术。 随机字符串生成技术用于生成随机的用户名、密码或文件名等。
在某些情况下,我们需要加密安全的字符串,即随机密码或密钥生成。 如果我们需要使用随机字符串作为随机用户名、文件名等,那么只使用随机字符串就足够了。 在本教程中,我们将讨论两种类型的随机字符串生成,如下所述。
在Python中使用random.choice()和string.join()生成随机字符串
random.choice(seq) 方法返回从作为输入提供的序列 seq 中随机选择的元素。 string.join(iterable) 方法使用提供的字符串值作为分隔符来连接 iterable 的元素,并返回结果字符串作为输出。
要在 Python 中生成随机字符串php随机字符串,我们需要为 random.choice() 方法提供一个字符序列,我们的代码将根据该序列生成随机字符串。 输入序列可以由小写字母、大写字母、数字、标点符号等组成。
我们可以分别使用 string.ascii_uppercase 和 string.ascii_lowercase 表示小写和大写序列,使用 string.ascii_letters 表示两者,使用 string.digits 表示数字序列,使用 string.punctuation 表示标点符号序列。
下面的示例代码演示了如何使用 Python 中的 random.choice() 和 string.join() 方法生成所需类型的随机字符串。
import string
import random
number_of_strings = 5
length_of_string = 8
for x in range(number_of_strings):
print(''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length_of_string)))
输出:
wOy5ezjl
j34JN8By
clA5SNZ6
D8K0eggH
6LjRuYsb
要生成加密安全的随机字符串,我们可以使用 random.SystemRandom() 方法,该方法从操作系统中的源生成随机数。
示例代码:
import string
import random
number_of_strings = 5
length_of_string = 8
for x in range(number_of_strings):
print(''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string)))
输出:
PEQBU72q
xuwUInGo
asVWVywB
SAsMRjka
CrbIpuR6
Python中使用uuid.uuid4()生成随机字符串
uuid.uuid4() 方法生成并返回一个随机 UUID。 UUID是一个128位的通用唯一标识符,用于标识系统或网络中的信息。
如果我们想从随机字符串生成随机且唯一的标识符php随机字符串,则此方法非常有用。 下面的示例代码演示了如何在Python中使用uuid.uuid4()方法获取随机字符串。
import uuid
print(uuid.uuid4())
输出:
440a93fe-45d7-4ccc-a6ee-baf10ce7388a
在Python中使用StringGenerator.render_list()生成随机字符串
StringGenerator().render_list() 是在 Python 中生成多个随机字符串的简单方法。 StringGenerator() 将正则表达式作为输入,该正则表达式定义用于生成随机字符串的字符。 在 renderlist(len, unique=) 方法中,len 指定包含随机字符串的输出列表的宽度。 如果我们想要唯一的输出字符串,我们可以将 unique 关键字参数设置为 True。
要使用此方法,首先需要安装 StringGenerator 模块。 下面的示例代码演示了如何使用 StringGenerator.render_list() 方法在 Python 中生成随机字符串。
from strgen import StringGenerator
StringGenerator("[ld]{10}").render_list(3,unique=True)
输出:
['m98xQHMlBI', 'V4O8hPMWfh', 'cBJk3XcGny']