Home » Python

Random string generation with upper case letters and digits in Python

Here, we are going to learn how to generate a random string with uppercase letters and digits in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on December 11, 2019

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,

  • 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.

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.

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.