Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nested strings for random.choice python

I have 4 lists and want to choose a random list and then choose a random item of it. this is my code but it doesn’t work properly. can you help please?

import random
w=['*', '&' ,'^', '%' ,'$' ,'#', '@' ,'!']
w1=['w','a','s','r','i','t','e','n','d','c']
w2=['W','A','S','R','I','T','E','N','D','C',]
w3=['1','2']

p=''
j=8
while j:
   e=random.choice(['w','w1','w2','w3'])
   q=random.choice(f'{f"{e}"}')
   p+=q
   j-=1

print(p)

and this is the wrong output that doesnt select from the lists:

w3www3ww

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use list comprehension and nest the random.choice calls like so:

import random

w = ['*', '&', '^', '%', '$', '#', '@', '!']
w1 = ['w', 'a', 's', 'r', 'i', 't', 'e', 'n', 'd', 'c']
w2 = ['W', 'A', 'S', 'R', 'I', 'T', 'E', 'N', 'D', 'C']
w3 = ['1', '2']

wlist = [w, w1, w2, w3]

p = ''.join(random.choice(random.choice(wlist)) for _ in range(8))

print(p)

Using list unpacking, you can shorten the code even more:

wlist = [*w, *w1, *w2, *w3]

p = ''.join(random.choice(wlist) for _ in range(8))

Make sure your list contains the variables, not strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading