Bimlesh Sharma
Bimlesh Sharma

Reputation: 306

How to generate list of string with Random Characters using python3

I tried with the below code but it seems not to give the intended output.

ran = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in range(10))

So the above code gives '6U1S75' but I want output like

['6U1S75', '4Z4UKK', '9111K4',....]

Please help.

Upvotes: 0

Views: 48

Answers (2)

Achxy_
Achxy_

Reputation: 1201

I thought this is elegant :

from string import digits, ascii_letters
from random import choices


def rand_list_of_strings(list_size, word_size, pool=ascii_letters + digits):
    return ["".join(choices(pool, k=word_size)) for _ in range(list_size)]

I used ascii_letters instead of ascii_uppercase to have both upper and lower case values, you can edit it to your suiting.

Example use of the above function :

>>> rand_list_of_strings(4, 5)
['wBSbH', 'rJoH8', '9Gx4q', '8Epus']
>>> rand_list_of_strings(4, 10) 
['UWyRglswlN', 'w0Yr7xlU5L', 'p0e6rghGMS', 'Z8zX2Vqyve']
>>>

The first argument is the list size, and the second argument is how large each consequent string should be, and the function invocation returns a list instance. Do not that this should not be used for cryptographic purposes.

Upvotes: 2

Giuppox
Giuppox

Reputation: 1629

Take a look at this.

list_size = 10
word_size = 4

ran = []

for i in range(list_size):
    rans = ''

    for j in range(word_size):
        rans += random.choice(string.ascii_uppercase + string.digits)

    ran.append(rans)

Though the above solution is clearer and should be preferred, if you absolutely want to do this with list comprehension...

list_size = 10
word_size = 4

ran = [
    ''.join([
        random.choice(string.ascii_uppercase + string.digits) 
        for j in range(word_size)
    ]) 
    for i in range(list_size)
]

Upvotes: 1

Related Questions