Answer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
or even shorter starting with Python 3.6 using random.choices():
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
A cryptographically more secure version: see this post
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.
string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a list comprehension to create a list of 'n' elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
Answer from Ignacio Vazquez-Abrams on Stack OverflowAnswer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
or even shorter starting with Python 3.6 using random.choices():
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
A cryptographically more secure version: see this post
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.
string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a list comprehension to create a list of 'n' elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
Using random.SystemRandom() instead of just random uses /dev/urandom on *nix machines and CryptGenRandom() in Windows. These are cryptographically secure PRNGs. Using random.choice instead of random.SystemRandom().choice in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.
If you're using python3.6 or above, you can use the new secrets module as mentioned in MSeifert's answer:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
The module docs also discuss convenient ways to generate secure tokens and best practices.
[beginner]How do i generate a list of random letters?
How to Generate Random Strings in Python
How to generate random strings in Python? - Stack Overflow
Python code that makes a word with random numbers and character in last
Videos
Don't use caps, numbers and letters; those are all constants available from the string module.
Don't assign j since it isn't used; name the iteration variable _ instead.
Replace your length / index / slice with a random.choices.
Don't call a variable list, since 1. it shadows an existing type called list, and 2. it isn't very descriptive.
Rather than your manual, unrolled string appending, just use ''.join().
A strictly equivalent implementation could be
import random
from string import ascii_lowercase, ascii_uppercase, digits
for _ in range(4):
fill_caps = random.choice(ascii_uppercase)
fill_number = random.choice(digits)
fill_letter = random.choice(ascii_lowercase)
choices = (fill_letter, fill_caps, fill_number)
word = ''.join(random.choices(choices, k=6))
print(word)
but your algorithm has some odd properties that, according to your comments, you did not intend. The output word will have the choice of only one lower-case letter, one upper-case letter and one digit. The simpler and less surprising thing to do is generate a word from any of those characters:
import random
from string import ascii_lowercase, ascii_uppercase, digits
choices = ascii_lowercase + ascii_uppercase + digits
for _ in range(4):
word = ''.join(random.choices(choices, k=6))
print(word)
I feel like the code can be made shorter. I just don't know how.
If you want your code to be shorter, you could use a single list, like this.
import random
def rand_str(size):
ascii_list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
res = ""
for i in range(size):
res += ascii_list[random.randint(0, len(ascii_list) - 1)]
return res
if __name__ == '__main__':
# Test
print(rand_str(16))
I tried using the random module but it only generates a single letter at a time. I want to generate more than 1 letters at a time. Cam i do it using the random module?
Edit: Not a list of characters but random characters
Edit2: Got the solution. Thanks everyone for the replies.
Hi Python programmers, here we are see How to Generate Random Strings in Python with the help of multiple Python modules and along with multiple examples.
In many programming scenarios, generating random strings is a common requirement. Whether you’re developing a password generator, creating test data, or implementing randomized algorithms, having the ability to generate random strings efficiently is essential. Thankfully, Python offers several approaches to accomplish this task easily. In this article, we’ll explore various methods and libraries available in Python for generating random strings.
-
Using the random Module
The random module in Python provides functions for generating random numbers, which can be utilized to create random strings. Here’s a basic example of how to generate a random string of a specified length using random.choice()
import random
import string
def generate_random_strings(length):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
# Example usage:
random_string = generate_random_strings(10)
print("Random String:", random_string)2. Using the Secrets Module
For cryptographic purposes or when higher security is required, it’s recommended to use the secrets module, introduced in Python 3.6. This Python built-in module provides functionality to generate secure random numbers and strings. Here’s how you can generate a random string using secrets.choice()
import secrets
import string
def generate_random_string(length):
return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))
# Example usage:
random_string = generate_random_string(10)
print("Random String:", random_string)This is how you can generate random Python strings for your applications.
I have written a complete article on this click here to read.
Thanks
Generating strings from (for example) lowercase characters:
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
Results:
>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'
Since this question is fairly, uh, random, this may work for you:
import uuid
print(uuid.uuid4())
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17