How to Generate a Random String of Any Length in Python


In this article, we show how to generate a random string with any characters and of any length in Python.

Why would you need to generate a random string in Python?

For many reasons.

You may have a website that generates random temporary passwords for users.

You may have a website that generates random ids for things such as videos, like youtube does for each of its uploaded videos.

You may have a website that generates a random username if a user tries to sign up for a username that is already taken. You then generate a random username and suggest usernames that aren't taken.

So the applications for generating random strings in Python is very useful for the real world.

So how can we do this in Python?

The way we do in this article is we create a variable and set it equal to all of the characters that we may want to be selected as a character in the string. It's the list of all the possible characters that can be selected to be in the string.

We then create another variable which will represent our random string generated.

We then use a for loop to loop through how many digits we want, with each digit randomly selected from the characters we specified using the random.choice() function.

The code to do this is shown below.

In our code, we generate a random string consisting of 6 characters.

So the following Python code above is able to generate an 6-digit random string from the characters we have provided in the characters variable. This characters variable contains 0-9,a-z,A-Z, -, and _

So the first thing we must do in our code is import the random module.

We then have a variable named characters, which we set equal to, 0-9,a-z,A-Z,-, and _

If you want to add more characters, then just add it to the end of this string. So if you want to add a "?" or anything else, just add it to the end of the string, and that character may be selected to appear in the random string.

We then create the variable, randomstring, which will be the variable that represents the 6-character random string in the end.

We then create a for loop that has 6 iterations, from 0 to 5; thus, a 6-character output will be the result. If you want a 10-character random string, then you change 6 to 10. If you want a 12-character random string, then you change 6 to 12.

We then set the randomstring variable equal to += random.choice(characters).

What this line does is it selects a random character from the characters variable for each of the 6 characters we make of the random string.

And this is all that is required to make a random string of any length in Python.

Related Resources

How to Create a Video Uploader with Python

HTML Comment Box is loading comments...