×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Random string generation with upper case letters and digits in Python

By Sapna Deraje Radhakrishna Last updated : December 21, 2024

Objective

The objective of this article is to Generation of the random alphanumeric string with uppercase and numbers.

Modules Required

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

Steps for Implementation

Step 1: Use string.ascii_uppercase

Use the string constant string.ascii_uppercase to get all uppercase letters in a single string. This constant contains all uppercase letters:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Step 2: Fetch Characters Randomly

Run a for loop for a specified number of times (x number of times) to fetch a character from the string constant using random.choice(), and append it to a 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.