Picking a Random Word In Python? [closed]

2019-03-25 09:23发布

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?

标签: python random
4条回答
欢心
2楼-- · 2019-03-25 10:08
str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))
查看更多
做个烂人
3楼-- · 2019-03-25 10:10

Use the random.choice() function:

>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
查看更多
再贱就再见
4楼-- · 2019-03-25 10:22
str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])
查看更多
相关推荐>>
5楼-- · 2019-03-25 10:28
>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'
查看更多
登录 后发表回答