Python – Generate Random String of Specific Length

Generate Random String with Python

A random string may be required for a system generated strong password, or such another scenarios.

Using random module of Python programming, you can generate such strings of specified length and specified character groups.

Step by step process

To generate a random string of specific length, follow these steps.

1. Choose Character Group

Choose the character groups from which you would like to pickup the characters. string class provides following character groups:

  • string.ascii_letters
  • string.ascii_lowercase
  • string.ascii_uppercase
  • string.digits
  • string.hexdigits
  • string.letters
  • string.lowercase
  • string.octdigits
  • string.punctuation
  • string.printable
  • string.uppercase
  • string.whitespace

2. Call random.choice()

Use random.choice() function with all the character groups (appended by + operator) passed as argument.

random.choice(string.ascii_uppercase + string.digits)

random.choice() picks one of the characters from the given string or characters.

3. Repeat picking the characters

Repeat this for N times, N being the length of the random string to be generated.

random.choice(string.ascii_uppercase + string.digits) for _ in range(N)

4. Join the picked characters.

Join all these N characters.

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

Example

Let us implement all the afore mentioned steps to generate a random string of specific length.

Python Program

import random
import string

def randStr(chars = string.ascii_uppercase + string.digits, N=10):
	return ''.join(random.choice(chars) for _ in range(N))

# Default length(=10) random string
print(randStr())

# Random string of length 7
print(randStr(N=7)) 

# Random string with characters picked from ascii_lowercase
print(randStr(chars=string.ascii_lowercase))

# Random string with characters picked from 'abcdef123456'
print(randStr(chars='abcdef123456'))
Run Code Copy

Output

4FH2R5SQ9D
8STJX1L
iihvalhdwc
d35bbbfcea

Summary

In this tutorial of Python Examples, we learned how to create a random string of specific length from given set of characters.

Related Tutorials

Code copied to clipboard successfully 👍