Say that I had a list containing 5 strings, and I wanted to print a random number of randomly generated strings from this list. Is there a simple way to do this?
I know multiple ways to print a single random string from this list, and multiple ways to print a set number of random strings from this set. The problem comes from wanting to print a random number of random strings from the list.
To get a set number of random strings (let’s say 2) I would do the following:
import random
my_list = ['a','b','c','d','e']
two_rand_strings = str(my_list[random.randint(0,4)]) + " " + str(my_list[random.randint(0,4)])
print(two_rand_strings)
I assume I need to create some sort of function to generate a random number of strings but I am new to python and scratching my head.
>Solution :
There is an API for that.
The random module has several options to select from a population such as a list. And if you want use use the same separator for each item in the string result, you can str.join them.
import random
my_list = ['a','b','c','d','e']
unique = " ".join(random.sample(my_list, k=2))
nonunique = " ".join(random.choices(my_list, k=2))