CODE:
from random import choice
from string import ascii_uppercase
print(''.join(choice(ascii_uppercase) for i in range(12)))
OUTPUT:
5 examples:
QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD
EDIT:
If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.
3 examples:
229945986931
867348810313
618228923380
Answer from Peter Varo on Stack OverflowCODE:
from random import choice
from string import ascii_uppercase
print(''.join(choice(ascii_uppercase) for i in range(12)))
OUTPUT:
5 examples:
QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD
EDIT:
If you need only digits, use the digits constant instead of the ascii_uppercase one from the string module.
3 examples:
229945986931
867348810313
618228923380
By Django, you can use get_random_string function in django.utils.crypto module.
get_random_string(length=12,
allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
Example:
get_random_string()
u'ngccjtxvvmr9'
get_random_string(4, allowed_chars='bqDE56')
u'DDD6'
But if you don't want to have Django, here is independent code of it:
Code:
import random
import hashlib
import time
SECRET_KEY = 'PUT A RANDOM KEY WITH 50 CHARACTERS LENGTH HERE !!'
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
How do I generate a random string (of length X, a-z only) in Python? - Stack Overflow
How to Generate Random Strings in Python
python - How to generate random strings that have variable length - Stack Overflow
how can i generate random strings of specific length?
Videos
''.join(random.choice(string.lowercase) for x in range(X))
If you want no repetitions:
import string, random
''.join(random.sample(string.ascii_lowercase, X))
If you DO want (potential) repetitions:
import string, random
''.join(random.choice(string.ascii_lowercase) for _ in xrange(X)))
That's assuming that by a-z you mean "ASCII lowercase characters", otherwise your alphabet might be expressed differently in these expression (e.g., string.lowercase for "locale dependent lowercase letters" that may include accented or otherwise decorated lowercase letters depending on your current locale).
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 can do this, however, you'll have to specify the maximum length that the string can be. You could always generate a random number for max_length as well.
import random, string
def random_string(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
max_length = 5
print(random_string(random.randint(1, max_length)))
Here are 5 test cases:
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
And their output is:
wl
crhxl
uvl
ty
iuydl
You can of course change the maximum length for the string by changing the max_length variable to whatever you'd like.
Variable string, variable length:
>>>import random, string
>>>max_rand_str_length = 10
>>> def genCustomString():
... return ''.join(random.choice(string.lowercase) for _ in range(random.choice(range(1, max_rand_str_length))))
...
>>> genCustomString()
'v'
>>> genCustomString()
'mkmylzc'
>>> genCustomString()
'azp'
>>> genCustomString()