How to Create a string of random characters using Python

In this tutorial we are going to learn about how to create a string of random characters using python. Here we use python because it is easy to understand and easy to write.

Create a string of random characters using Python

Method 1:Generate a random string using random.choices()

This random.choices()_function of a random module can help us achieve this task, and provides a one-linear alternative to a whole loop that might be required for this particular task. The choices() method returns multiple random elements from the list with replacement. weight the possibility of each result with the weights parameter or the cum_weights parameter. The elements can be a string, a range, a list ,a list, a tuple or any other kind of sequence. parameters are sequence, weights, cum_weights, k.

Methods 2:Generate random string using secrets, choice()

we can generate random strings and passwords in python using secrets. choice()..for cryptographically more secure random numbers, thisĀ  function of the secret module can be used as its internal algorithm is framed in a way to generate less predictable random numbers.

import string    
import random
G = 10 
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = G))    
print("The randomly generated string is : " + str(ran)) r

Here we used import string and import random that means we are importing the string and random in our code because to use these in our code in order to get our required output.

OUTPUT :

The randomly generated string is : JVM7AET12P


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top