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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.