In this lesson, you will learn how to create a random string and passwords in Python.
Table of contents
- String Constants
- How to Create a Random String in Python
- Random String of Lower Case and Upper Case Letters
- Random String without Repeating Characters
- Create Random Password with Special characters, letters, and digits
- Generate a random alphanumeric string of letters and digits
- Generate a random string token
- Use the StringGenerator module to generate a random string
- Next Steps
String Constants
Below is the list of string constants you can use to get a different set of characters as a source for creating a random string.
| Constant | Description |
|---|---|
ascii_lowercase | Contain all lowercase letters |
ascii_uppercase | Contain all uppercase letters |
ascii_letters | Contain both lowercase and uppercase letters |
digits | Contain digits ‘0123456789’. |
punctuation | All special symbols !”#$%&'()*+,-./:;<=>?@[\]^_`{|}~. |
whitespace | Includes the characters space, tab, linefeed, return, formfeed, and vertical tab [^ \t\n\x0b\r\f] |
printable | characters that are considered printable. This is a combination of constants digits, letters, punctuation, and whitespace. |
How to Create a Random String in Python
We can generate the random string using the random module and string module. Use the below steps to create a random string of any length in Python.
- Import string and random module
The string module contains various string constant which contains the ASCII characters of all cases. It has separate constants for lowercase, uppercase letters, digits, and special symbols, which we use as a source to generate a random string.
Pass string constants as a source of randomness to the random module to create a random string - Use the string constant ascii_lowercase
The
string.ascii_lowercasereturns a list of all the lowercase letters from ‘a’ to ‘z’. This data will be used as a source to generate random characters. - Decide the length of a string
Decide how many characters you want in the resultant string.
- Use a for loop and random choice() function to choose characters from a source
Run a for loop till the decided string length and use the random choice() function in each iteration to pick a single character from the string constant and add it to the string variable using a
join()function. print the final string after loop competition - Generate a random Password
Use the
string.ascii_letters,string.digits, andstring.punctuationconstants together to create a random password and repeat the first four steps.
Example to generate a random string of any length
Output:
Random string of length 8 is: ijarubtd Random string of length 6 is: ycfxbs Random string of length 4 is: dpla
- The random choice() function is used to choose a single item from any sequence and it can repeat characters.
- The above random strings contain all lower case letters. If you want only the uppercase letters, then use the
string.ascii_uppercaseconstant instead in the place of astring.ascii_lowercase.
Random String of Lower Case and Upper Case Letters
In Python, to generate a random string with the combination of lowercase and uppercase letters, we need to use the string.ascii_letters constant as the source. This constant contains all the lowercase and uppercase letters.
Example
Output:
WxQqJQlD NoCpqruK
Random string of specific letters
If you wanted to generate a random string from a fixed set of characters, please use the following example.
Random String without Repeating Characters
Note: The choice() method can repeat characters. If you don’t want repeated characters in a resultant string, then use the random.sample() method.
Output:
wxvdkbfl ztondpef voeduias
Warning: As you can see in the output, all characters are unique, but it is less secure because it will reduce the probability of combinations of letters because we are not allowing repetitive letters and digits.
Create Random Password with Special characters, letters, and digits
A password that contains a combination of characters, digits, and special symbols is considered a strong password.
Assume, you want to generate a random password like: –
- ab23cd#$
- jk%m&l98
- 87t@h*ki
We can generate a random string password in Python with letters, special characters, and digits using the following two ways.
- Combine the following three constants and use them as a data source for the
random.choice()function to select random characters from it.string.ascii_letters: To include letters from a-z and A-Zstring.digits: To include digits from 1 to 10string.punctuation: to get special symbols
- Use the
string.printableconstant andchoice()function. Thestring.printablecontains a combination of digits, ascii_letters (lowercase and uppercase letters), punctuation, and whitespace.
Example
Output:
Random password is: 6(I3goZ}
Using the string.printable
Output
Random password is: hY*34jj.
Random password with a fixed count of letters, digits, and symbols
It is a widespread use case that passwords must contain some count of digits and special symbols.
Let’s see how to generate a random password that contains at least one lowercase letter, one uppercase letter, one digit, and one special symbol.
Steps: –
- First, select the number of random lowercase and uppercase letters specified
- Next, choose the number of random digits
- Next, choose the number of special symbols
- Combine both letters, digits, and special symbols into a list
- At last shuffle the list
- Convert list back to a string
Generate a secure random string and password
Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random data using synchronization methods to ensure that no two processes can obtain the same data simultaneously.
If you are producing random passwords or strings for a security-sensitive application, then you must use this approach.
If you are using Python version less than 3.6, then use the random.SystemRandom().choice() function instead of random.choice().
If you are using a Python version higher than 3.6 you can use the secrets module to generate a secure random password.
Use secrets.choice() function instead of random.choice()
Generate a random alphanumeric string of letters and digits
We often want to create a random string containing both letters and digits such as ab23cd, jkml98, 87thki. In such cases, we use the string.ascii_letters and string.digits constants to get the combinations of letters and numbers in our random string.
Now, let’s see the to create a random string with the combination of a letter from A-Z, a-z, and digits 0-9.
Random alphanumeric string with a fixed count of letters and digits
For example, I want to create a random alpha-numeric string that contains 5 letters and 3 numbers.
Example
Output:
First random alphanumeric string is: v809mCxH Second random alphanumeric string is: mF6m1TRk
Generate a random string token
The above examples depend on String constants and random module functions. There are also other ways to generate a random string in Python. Let see those now.
We can use secrets.token_hex() to get a secure random text in hexadecimal format.
Output:
Secure hexadecimal string token 25cd4dd7bedd7dfb1261e2dc1489bc2f046c70f986841d3cb3d59a9626e0d802
Generate universally unique secure random string Id
The random string generated using a UUID module is suitable for the Cryptographically secure application. The UUID module has various functions to do this. Here in this example, we are using a uuid4() function to generate a random string Id.
Use the StringGenerator module to generate a random string
The StringGenerator module is not a part of a standard library. However, if you want you can install it using pip and start using it.
Steps: –
pip install StringGenerator.- Use a
render()function of StringGenerator to generate randomized strings of characters using a template
Let see the example now.
Next Steps
I want to hear from you. What do you think of this article? Or maybe I missed one of the ways to generate random string in Python. Either way, let me know by leaving a comment below.
Also, try to solve the random module exercise and quiz to have a better understanding of working with random data in Python.
Practice Problem
Create a random alphanumeric string of length ten that must contain at least four digits. For example, the output can be anything like 1o32WzUS87, 1P56X9Vh87

Vishal you’re such a very best teacher. All your python tutorials are always best and understandable. I’m so proud of you. Thank you for sharing this information and education to us. You’re such the most valuable person in our lives. We highly appreciate you a lot for your great work. I’ve learnt so much in your tutorials and I mastered a lot of information and a lot of good skills of programming. I’m so proud of you.
In the random module is the warning
> Warning
>
> The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.
please don’t use these for passwords
If you are producing random passwords or strings for a security-sensitive application, then you can use the secrets module.
How can I create a password generator that generates a random password based on length and parameters input from user? It also needs to validate the user’s input to ensure it’s an integer for length. It also needs to validate the user’s parameters if they choose yes or no on using upper, lower, digits, and punctuation.
Nice job! How do I generate more than one password at a time? Say I want to generate 100 random passwords?
Thanks!
just put
print(100)How do I create a password generator with certain amounts of each letter like 5 uppercase 3 lower case 2 numbers and so on.
I think there’s an example of a For loop for choosing
random.choice(string.ascii_lowercase)2 times then you addrandom.choice(string.ascii_uppercase)3 timesOie Vishal, Parabéns pelo seu trabalho em desenvolver essa plataforma de estudos, em programação e linguagem de computacional, já rodei acredito que umas 50 vezes por todo o site e acredite sempre consigo aprender coisas novas. a solução pro exercício na prática, ficou assim.
Oie Vishal, Parabéns pelo seu trabalho em desenvolver essa plataforma de estudos, em programação e linguagem de computacional, já rodei acredito que umas 50 vezes por todo o site e acredite sempre consigo aprender coisas novas. a solução pro exercício na pratica, ficou assim.
#saída:
string alfanumérica aleatória: yCvPF9l865
string alfanumérica aleatória: 5EU62PFW8D
Hi Vishal,
Great article! In my journey to become a sharper automation engineer, this explanation greatly helped me. Although, I came here after reading Secrets module. Seemed easy to follow through. Thank you!!
Reference: https://docs.python.org/3/library/secrets.html#recipes-and-best-practices
Here is my trial!
I basically understood, even though I’m a beginner in python.
I figured this out myself, I emptied more things, it may not make much sense, but suddenly it popped out of my head when analyzing the scripts:
(Many strings are separate because I didn’t need a value of 0.) 🙂
Wonderful job;
Greate article ever seen!
Can the function please return a value …
Hi there, thank you for your kind offerings and hard work. Your piece of code is sitting nicely in my program. I am using it to create a random temporary file.
:¬) pj
Nice article on generating random password.
Sudhir, I am glad you liked it.
I want to generate a list of 50 proper nouns say country names or fruit names or city names randomly from the list of alphabets provided. The words generated will be meaningful, no random words formed and should not be taken from any predefined list of files. How do I do this? I used ranom word library from PyPi org but the words produced are less common and cannot cluster them in a particular category. How do I achieve this through Python code? Is there a thesaurus or English dictionary library in Python?
Hey Indranil, You can check this. hope it helps
https://stackoverflow.com/questions/55073163/english-dictionary-library-in-python3
https://stackoverflow.com/questions/3788870/how-to-check-if-a-word-is-an-english-word-with-python
https://pypi.org/project/Vocabulary/https://pypi.org/project/oxforddictionaries/
how can I create Random Password Generator API (8 to 80 characters in length)?