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

2021-01-11 10:15:35 浏览数 (1)

参考链接: Python字符串| ascii_uppercase

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

0 人点赞