在 Python 中生成随机字符串 您所在的位置:网站首页 python随机输出一个数 在 Python 中生成随机字符串

在 Python 中生成随机字符串

2023-09-23 03:31| 来源: 网络整理| 查看: 265

在 Python 中使用 random.choice() 和 string.join() 方法生成随机字符串 在 Python 中使用 uuid.uuid4() 方法生成随机字符串 在 Python 中使用 StringGenerator.render_list() 方法生成随机字符串

在本教程中,我们将研究在 Python 中生成随机字符串的各种方法。随机字符串生成技术用于生成随机的用户名,密码或文件名等。

全素巧克力南瓜乳酪蛋糕 (...

Please enable JavaScript

全素巧克力南瓜乳酪蛋糕 (免烤,無麵粉) Vegan Chocolate Pumpkin Cheesecake (No-Bake + Gluten-Free)

在某些情况下,我们需要加密安全的字符串,即随机密码或密钥生成。如果我们需要使用随机字符串作为随机的用户名和文件名等,仅使用随机字符串就足够了。在本教程中,我们将讨论两种类型的随机字符串生成,下面将对此进行说明。

在 Python 中使用 random.choice() 和 string.join() 方法生成随机字符串

random.choice(seq) 方法从作为输入提供的序列 seq 中返回一个随机选择的元素。string.join(iterable) 方法通过使用提供的 string 值作为分隔符来连接 iterable 的元素,并返回结果字符串作为输出。

要在 Python 中生成随机字符串,我们需要向 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 位长的通用唯一标识符,用于标识系统或网络中的信息。

如果我们要从随机字符串中生成随机且唯一的标识符,则此方法很有用。下面的示例代码演示了如何使用 uuid.uuid4() 方法在 Python 中获取随机字符串。

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("[\l\d]{10}").render_list(3,unique=True)

输出:

['m98xQHMlBI', 'V4O8hPMWfh', 'cBJk3XcGny']


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有