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.
How to Generate Random Strings in Python
Python random string/text/code generator with fixed length and some characters - Stack Overflow
randomness - How to generate a random string in Python for a mission-critical application - Cryptography Stack Exchange
how can i generate random strings of specific length?
Videos
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
You're almost there. I've just tweaked it a little - you could adjust it as is:
import random
numcount = 5
fstring = ""
length_of_code_you_want = 12
position_to_keep_constant_1 = 2 # first position to keep constant is position 3, index 2
position_to_keep_constant_2 = 6 # 2nd position to keep constant is position 7, index 6
constant_1 = "J" # the value of the constant at position 3
constant_2 = "L" # the value of the constant at position 7
for num in range(length_of_code_you_want): #strings are 19 characters long
if random.randint(0, 1) == 1:
x = random.randint(1, 8)
x += 96
fstring += (chr(x).upper())
elif not numcount == 0:
x = random.randint(0, 9)
fstring += str(x)
numcount -= 1
list_out = list(fstring)
list_out[position_to_keep_constant_1] = str(constant_1)
list_out[position_to_keep_constant_2] = str(constant_2)
string_out = "".join(list_out)
print(string_out)
Not sure about the legality of that, but the problem is easy enough.
import random
import string
value_of_seven = 7
value_of_three = 3
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
_string = ''.join(random.choice(letters) for i in range(stringLength))
print ("Random String is ", randomString() )
return _string
x = 0
string_set = set()
while x <= 10:
x += 1
rand_str = randomString()
if rand_str[-1, 3] is value_of_seven and rand_str[1, 3] is value_of_three:
string_set.add(rand_str)
But we really need to know, just letters lower case? Upper case?
Also if your trying to generate them with the same things in those places you would still slice at the same point and add the string on the end.
Ok here is working version with your requirements
import random
import string
value_of_seven = '7'
value_of_three = '3'
def _random(stringLength=5):
"""Generate a string of Ch/digits """
lett_dig = string.ascii_letters + string.digits
return ''.join(random.choice(lett_dig) for i in range(stringLength))
if __name__ == '__main__':
s = _random()
s = s[:2] + value_of_three + s[2:]
s = s[:6] + value_of_seven + s[6:]
print(s)