Open In App

Python Program to Generate Random String With Uppercase And Digits

Last Updated : 24 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Generating a series of random strings can help create security codes. Besides, there are many other applications for using a random string generator, for instance, obtaining a series of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting of random characters and digits. Let’s see how we can create a random string generator.

Method 1: Using for loop

For generating random strings only with uppercase letters and digits using for loop, we require to import built-in python modules, namely random and string.

Python3




# Random string generation using uppercase letters and digits
# YTDWIU75
import random
import string
 
 
def id_generator(length):
 
    # initializing empty string
    return_str = ""
 
    # generating a string containing A-Z and 0-9
    data = string.ascii_uppercase + '0123456789'
 
    for i in range(length):
 
        # generating random strings
        return_str += random.choice(data)
 
    # print result
    print("The generated random string : " + str(return_str))
 
 
# function call
id_generator(7)


Output

The generated random string : 0ZM1C29

 

Method 2: Using secrets.choice()

The secrets module generates cryptographically secure random numbers suitable for managing data such as passwords, account authentication, and security tokens.

Python3




import secrets
import string
 
# initializing empty string
return_str = ""
   
# initializing size of string
N = 7
 
# generating random strings using secrets.choice()
return_str = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
                     for i in range(N))
 
# print result
print("The generated random string : " + str(return_str))


Output

The generated random string : 26SJ8IA

 

Method 3: Using random.choices()

The third approach is by random.choices. The choices() function returns a collection of random elements with replacement.

Python3




import random
import string
 
# initializing empty string
return_str = ""
   
# initializing size of string
N = 7
 
# generating random strings using random.choices()
return_str = ''.join(random.choices(
    string.ascii_uppercase + string.digits, k=N))
 
# print result
print("The generated random string : " + str(return_str))


Output

The generated random string : H4ICGAZ

Method 4: Using secrets module

 step-by-step algorithm for implementing this approach:

  1. Import the secrets and string modules.
  2. Define the id_generator function with a single argument, length.
  3. Initialize an empty string, return_str.
  4. Generate a string containing uppercase letters and digits (0-9) using string.ascii_uppercase and the string literal ‘0123456789’.
  5. Use a list comprehension to generate a list of length random characters from the data string using secrets.choice(data).
  6. Use the join method to concatenate the characters in the list into a single string.
  7. Assign the resulting string to return_str.
  8. Print the generated random string with a message.
  9. Return the generated string.

Python3




import secrets
import string
 
def id_generator(length):
 
    # initializing empty string
    return_str = ""
 
    # generating a string containing A-Z and 0-9
    data = string.ascii_uppercase + '0123456789'
 
    # using the secrets module to generate the random string
    return_str = ''.join(secrets.choice(data) for i in range(length))
 
    # print result
    print("The generated random string : " + str(return_str))
 
# function call
id_generator(7)


Output

The generated random string : YB7HXVH

The time complexity of this algorithm is O(n), where n is the length of the string to be generated. The secrets.choice() method is called n times to generate the random characters, and the join() method is called once to concatenate the characters into a string.

The auxiliary space of this algorithm is also O(n), where n is the length of the string to be generated. This is because the function creates a list of length n to hold the random characters, and then concatenates them into a string of length n. The space used by the data string and the return_str variable is constant, regardless of the length of the generated string.



Similar Reads

Python - Random uppercase in Strings
Given a String, the task is to write a Python program to convert its characters to uppercase randomly. Examples: Input : test_str = 'geeksforgeeks' Output : GeeksfORgeeks Explanation : Random elements are converted to Upper case characters. Input : test_str = 'gfg' Output : GFg Explanation : Random elements are converted to Upper case characters.Me
4 min read
Python Program to Generate Random binary string
Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or "1" using randint function from random package. Ap
2 min read
Python | Generate random string of given length
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let's discuss certain ways in which this can be performed in Python. Here, we will use Random string ge
3 min read
Python Program to convert String to Uppercase under the Given Condition
Given a String list, the task is to write a Python program to convert uppercase strings if the length is greater than K. Examples: Input : test_list = ["Gfg", "is", "best", "for", "geeks"], K = 3 Output : ['Gfg', 'is', 'BEST', 'for', 'GEEKS'] Explanation : Best has 4 chars, hence BEST is uppercased.Input : test_list = ["Gfg", "is", "best", "for", "
5 min read
Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
How to generate a random number between 0 and 1 in Python ?
The use of randomness is an important part of the configuration and evaluation of modern algorithms. Here, we will see the various approaches for generating random numbers between 0 ans 1. Method 1: Here, we will use uniform() method which returns the random number between the two specified numbers (both included). Code: C/C++ Code import random pr
1 min read
Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
Prerequisites: Regular Expression in Python Given a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python. Examples: Input : "ThisIsGeeksforGeeks!, 123" Output :No. of uppercase characters = 4No. of lowercase characters = 15No. of numerical char
2 min read
Python - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed. Method #1: Using choice() + list comprehen
3 min read
Python | Generate random number except K in list
Sometimes, while working with Python, we can have a problem in which we need to generate random numbers. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random numbers from a list except K. Let's discuss certain ways in which this task can be performed. Method #1 : Using choice() + list compr
6 min read
Article Tags :
Practice Tags :