dimanche 13 août 2023

Variable with x number of strings from list in Python

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.




Aucun commentaire:

Enregistrer un commentaire