How to generate a random string in Python?
Tags: python, beginners, tutorial
Published: 2021-10-28 12:03:07

In this short tutorial, we look at how we can generate a random string in Python. We also look at all the various types of string that can be generated.

### Table of Contents:
- [Importing string and random modules](#importing-string-and-random-modules)
- [Generate random string Python](#generate-random-string-python)
    - [String in different cases](#string-in-different-cases)
- [Cryptographically Secure strings](#cryptographically-secure-strings)
- [Closing thoughts](#closing-thoughts)


## Importing string and random modules:
In order to generate random strings in Python, we use the string and random modules. The string module contains Ascii string constants in various text cases, digits, etc. The random module on the other hand is used to generate pseudo-random values. In the last method, we would be using the secrets module to help us generate cryptographically secure strings.

## Generate random string Python:
Random strings are commonly generated and used widely. Although they serve a large number of use cases, the most common ones are random placeholder usernames, random phone numbers, passwords, etc.

### String Module
Before we use the string module to generate a random string, let us look at the various types of string constants available.
- String.ascii_letters - returns a string of letters containing various cases.
- String.ascii_lowercase - returns a string with letters in lowercase.
- String.ascii_uppercase - returns a string with letters in uppercase.
- String.digits - returns a string containing digits
- String.punctuation - returns a string containing punctuations
I have listed the most commonly used string constant. However, you can view the entire list on the module documentation (String module).

### Random Module:
The random module is quite straightforward. It helps us pick a character at random. We use this method to pick characters from the string constant.
However, there are two important sequences that you should be aware of:
- Random.choices - returns elements at random. Here characters can not be unique.
- Random.sample - returns unique elements.
So while generating a random string in Python, If you are okay with repeating characters you can use the first method, and the second if you want unique characters.

### Code and Explanation:
```python
import random
import string

print(random.choices(string.ascii_lowercase))
```
This code generated returns one character at random. You can change the string constant method based on the characters you want.

Now let us write the code to generate a string of length 5.
```python
import random
import string

print(''.join(random.choices(string.ascii_lowercase, k=5)))
```
For this, we pass another argument ‘k’ which denotes the size of the string. This method returns a list of characters, and hence we use the join method to convert it into a string.

### String in different cases:
In the previous method, we used string.ascii_lowercase. Let us try the letters constantly, we can also concatenate two different types of constants.

Random string in uppercase:
```python
import random
import string

print(''.join(random.choices(string.ascii_uppercase, k=5)))
```
Using String.ascii.letters:
```python
import random
import string

print(''.join(random.choices(string.ascii_letters, k=5)))
```
Concatenating different types of string constants:
```python
import random
import string

print(''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=5)))
```
I haven’t provided output snippets as my output would vary from yours. Also, in all the methods I have used the random.choices. Please feel free to try it out using the random.sample as well.

## Cryptographically Secure strings:
While we could use the random method to generate random string in Python, the string generated is not cryptographically secure. Hence it is not recommended while creating temp passwords.

Python versions 3.6 and greater have a better way to generate a cryptographically secure random string. This method makes use of the secrets & string methods. Secrets are very similar to the random method, you can read more about it here.

Code and Explanation:
```python
import secrets
import string

print(''.join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase) for i in range(7)))
```
The secret methods do not have a .choices method which takes a second argument. Hence we use a loop and get the range to the number of characters.

## Closing thoughts:
Both methods can be used to generate a random string in Python. However, which method you use would largely depend on your use case.

A common mistake I have seen beginners make is forgetting to import the module before they use it. Do keep this in mind while you practice using the methods with other string contents.