Picking a Random Word In Python? [closed]

2019-03-25 09:27发布

问题:

How would I pick a random word from a long list of words (in one list not multiple) and then print it to the user?

回答1:

Use the random.choice() function:

>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks


回答2:

>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'


回答3:

str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))


回答4:

str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])


标签: python random