Reputation: 5477
In Python 3, how would I print a random word from a list of words?
Upvotes: 20
Views: 121194
Reputation: 339
str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])
Upvotes: 3
Reputation: 339
str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))
Upvotes: 3
Reputation: 13963
>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'
Upvotes: 6
Reputation: 992697
Use the random.choice()
function:
>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
Upvotes: 35