Reputation: 52675
I need to generate random 32-digit number along with 15-character string to get something like 09826843-5112-8345-7619-372151470268
and qcRtAhieRabnpUaQ
. I use following code to generate number:
import random
"-".join(['%08d' % random.randrange(0, 10e7),
'%04d' % random.randrange(0, 10e3),
'%04d' % random.randrange(0, 10e3),
'%04d' % random.randrange(0, 10e3),
'%012d' % random.randrange(0, 10e11)])
Is there a similar way to create case insensitive 15-char string with just random
module?
Upvotes: 1
Views: 249
Reputation: 7261
import random
rand_cap = [chr(random.randint(65, 90)) for i in range(7)]
rand_small = [chr(random.randint(97, 122)) for i in range(7)]
rand_chars_list = rand_cap + rand_small
random.shuffle(rand_chars_list)
rand_chars = ''.join(rand_chars_list)
Upvotes: 1
Reputation: 10221
import numpy as np
import random
import string
def random_string(num_chars, symbols):
return "".join(random.choice(symbols)
for _ in range(num_chars))
def random_string2(num_chars, symbols, replace=True):
"""Random string with replacement option"""
symbols = np.asarray(list(symbols))
return "".join(np.random.choice(symbols, num_chars, replace))
def main():
print(random_string(15, string.ascii_letters))
print(random_string2(15, string.ascii_letters, False))
print(random_string2(15, string.ascii_letters, True))
if __name__ == "__main__":
main()
Note that elements in string need not be unique (which I presume to be the case since "qcRtAhieRabnpUaQ" has 2 'a').
If you want the elements to be unique, then @Sergey Gornostaev's solution is probably the most elegant, but that will impose the number of unique elements in ascii_letters as the longest string you can generate.
Upvotes: 3
Reputation: 7797
import random
import string
''.join(random.sample(string.ascii_letters, 15))
import uuid
str(uuid.uuid4())
Upvotes: 3