+ 1

Generating random strings

Can you generate random strings similar to generating random numbers using the randint function? If you can’t, than how do you accomplish that task?

14th May 2020, 8:07 PM
Zach Janzen
6 Réponses
+ 4
You can do this tho a=[firststring ,secondstring,t hirdstring] and then use random.choice(a) it will output the random string from list a as you might have guessed by the name !
14th May 2020, 8:08 PM
Abhay
Abhay - avatar
+ 1
Zach Janzen if you mean a string with random characters, thats what you should do. 1) Specify a length variable for string. 2) Create an empty string. 3) create random numbers for example, between 97 (for 'a'), 122 (for 'z') convert it to char with chr() function. 4) then add it to string Then you (probably) get a meaningless word.
14th May 2020, 8:29 PM
Mustafa K.
Mustafa K. - avatar
+ 1
"Generating" random strings sounds to me, that new strings should be generated from a given range of characters and in a defined length or in a random length. If this is whta you mean, just give a feedback. Thanks.
14th May 2020, 8:37 PM
Lothar
Lothar - avatar
+ 1
Lothar, what i mean is like if i would like it to choose to print 3 different words but it can only choose 1 to print. For example, if i wanted it to print hello, hi, or greetings but it would only pront one of those and it would print a random one.
14th May 2020, 9:52 PM
Zach Janzen
+ 1
That's what I thought , otherwise who would want a meaningless string, tho I still coded it anyway lol import random def random_string(len): i=0 b="" while i<len: i+=1 letter=random.choice(list(i for i in range(65,92))+list(j for j in range(97,124))) character=chr(letter) b+=character return b print(random_string(6))
14th May 2020, 9:57 PM
Abhay
Abhay - avatar
0
Thanks fellow programmer!
14th May 2020, 8:28 PM
Zach Janzen