How To Generate a Random String in Python
Created
Modified
Using List Comprehension
List comprehensions provide a concise way to create lists. See the following example:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import random
import string
# a string of size n
letters = string.ascii_letters
n = 6
lst = ''.join(random.choice(letters) for i in range(n))
print(lst)
nYVWGX uUeAAJ
Using random.choices Function
Starting with Python 3.6 using random.choices()
. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import random
import string
# a string of size n
letters = string.ascii_letters
n = 6
lst = ''.join(random.choices(letters, k=n))
print(lst)
Gzmslz gdESzU
From Python 3.6, random.choices
would be faster.
random.choice
is not secure either. Use random.SystemRandom().choice()
or use os.urandom() directly.
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import random
import string
# a string of size n
letters = string.ascii_letters
n = 6
lst = ''.join(random.SystemRandom().choices(letters, k=n))
print(lst)
wxTUTI QwBInx
Using uuid Module
This module provides immutable UUID objects. uuid4() creates a random UUID.
If UUIDs are okay for your purposes, use the built-in uuid package. See the following example:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import uuid
# a string of size n
n = 6
lst = uuid.uuid4().hex[0:n]
print(lst)
465fc7 fbcccb