Python Program to Generate Random String With Uppercase And Digits
Last Updated :
05 Sep, 2024
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.
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.
Python
# 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)
OutputThe generated random string : 0ZM1C29
The secrets module generates cryptographically secure random numbers suitable for managing data such as passwords, account authentication, and security tokens.
Python
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))
OutputThe generated random string : 26SJ8IA
The third approach is by random.choices. The choices() function returns a collection of random elements with replacement.
Python
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))
OutputThe generated random string : H4ICGAZ
Method 4: Using secrets module
step-by-step algorithm for implementing this approach:
- Import the secrets and string modules.
- Define the id_generator function with a single argument, length.
- Initialize an empty string, return_str.
- Generate a string containing uppercase letters and digits (0-9) using string.ascii_uppercase and the string literal '0123456789'.
- Use a list comprehension to generate a list of length random characters from the data string using secrets.choice(data).
- Use the join method to concatenate the characters in the list into a single string.
- Assign the resulting string to return_str.
- Print the generated random string with a message.
- Return the generated string.
Python
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)
OutputThe 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 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
2 min read
Generate Random String Without Duplicates in Python When we need to create a random string in Python, sometimes we want to make sure that the string does not have any duplicate characters. For example, if we're generating a random password or a unique identifier, we might want to ensure each character appears only once. Using random.sample()Using ran
2 min read
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
4 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.
5 min read
Python program to Uppercase selective indices Given a String perform uppercase to particular indices. Input : test_str = 'geeksgeeksisbestforgeeks', idx_list = [5, 7, 3, 2, 6, 9] Output : geEKsGEEkSisbestforgeeks Explanation : Particular indices are uppercased. Input : test_str = 'geeksgeeksisbestforgeeks', idx_list = [5, 7, 3] Output : geeKsGe
7 min read
Python program to uppercase the given characters Given a string and set of characters, convert all the characters that occurred from character set in string to uppercase() Input : test_str = 'gfg is best for geeks', upper_list = ['g', 'e', 'b'] Output : GfG is BEst for GEEks Explanation : Only selective characters uppercased.Input : test_str = 'gf
7 min read
Python Program to Converts Characters To Uppercase Around Numbers Given a String, the following program converts the alphabetic character around any digit to its uppercase. Input : test_str = 'geeks4geeks is best1 f6or ge8eks' Output : geekS4Geeks is besT1 F6Or gE8Ek Explanation : S and G are uppercased as surrounded by 4.Input : test_str = 'geeks4geeks best1 f6or
8 min read
Python program to find maximum uppercase run Giving a String, write a Python program to find the maximum run of uppercase characters. Examples: Input : test_str = 'GeEKSForGEEksISBESt' Output : 5 Explanation : ISBES is best run of uppercase. Input : test_str = 'GeEKSForGEEKSISBESt' Output : 10 Explanation : GEEKSISBES is best run of uppercase.
2 min read
Ways to split strings on Uppercase characters - Python Splitting strings on uppercase characters means dividing a string into parts whenever an uppercase letter is encountered.For example, given a string like "CamelCaseString", we may want to split it into ["Camel", "Case", "String"]. Let's discuss different ways to achieve this.Using Regular Expression
3 min read
Generate Random Strings for Passwords in Python A strong password should have a mix of uppercase letters, lowercase letters, numbers, and special characters. The efficient way to generate a random password is by using the random.choices() method. This method allows us to pick random characters from a list of choices, and it can repeat characters
2 min read