在Python中使用大写字母和数字生成随机字符串

The objective of this article is to Generation of the random alphanumeric string with uppercase and numbers. To generate the random string, we could use the following modules from python,

本文的目的是生成带有大写字母和数字的随机字母数字字符串 。 要生成随机字符串,我们可以使用python中的以下模块,

  • random module – for random string generation

    随机模块 –用于随机字符串生成

  • String module – for upper case alphabets

    字符串模块 –用于大写字母

Step 1: Use the string constant string.ascii_uppercase to get all uppercase letters in a single string. The string.ascii_uppercase constant contains all uppercase letters i.e., ABCDEFGHIJKLMNOPQRSTUVWXYZ.

步骤1:使用字符串常量string.ascii_uppercase可以在单个字符串中获取所有大写字母。 string.ascii_uppercase常数包含所有大写字母,即ABCDEFGHIJKLMNOPQRSTUVWXYZ

Step 2: Run for loop for x number of times fetch a character from the string constant using random.choice() and append it to string variable using the join function. The choice function is used to fetch a single character.

步骤2:运行for循环x次,使用random.choice()从字符串常量中获取字符,然后使用join函数将其附加到字符串变量中。 选择功能用于获取单个字符。

Example implementation

示例实施

# importing the modules
import random
import string

# declaring the string length
string_length = 10 

# generating only uppercase
letters = string.ascii_uppercase 
print(''.join(random.choice(letters) for i in range(string_length)))

# generating both uppercase and numbers
letters_digits = string.ascii_uppercase + string.digits 
print(''.join(random.choice(letters_digits) for i in range(string_length)))

Output

输出量

SOVULPIZJT
4W0J0D0BTY


翻译自: https://www.includehelp.com/python/random-string-generation-with-upper-case-letters-and-digits.aspx

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值