-3

I have given three strings 'aaa','bbb','ccc' and i want to print any one of these at random, how to do it?

pg7064
  • 1
  • 1
  • `import random; choices = ['aaa','bbb','ccc']; print(random.choice(choices))` –  Jan 21 '21 at 09:05
  • 1
    Does this answer your question? [How to randomly select an item from a list?](https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list) – stuckoverflow Jan 21 '21 at 09:10

4 Answers4

1

Use random

import random
print(random.choice(['aaa','bbb','ccc']))
Mohil Patel
  • 437
  • 3
  • 9
1
from random import choice

strings = ['aa','bb','cc']
print(choice(strings))
scotty3785
  • 6,763
  • 1
  • 25
  • 35
-1

Given you have your strings in an array you can get the random integer in range (between 1 and 3 in your case) using random.randint:

import random
a=['aaa','bbb','ccc']
rnd=random.randint(1,3)
print(a[rnd])
-1

Build a list with all the String options. Next generate a random whole number in the range between 0 and the highest index of the list. This number becomes the index for the selected string.

random() gives you a random float value between 0 and 1.

something like this should work

>>> from random import random
>>> options = ['aaa','bbb','ccc']
>>> selected_idx = int(random() * len(options))
>>> options[selected_idx]
'bbb'

ConstantinB
  • 161
  • 9