带编号变量的随机文本

2024-04-19 00:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图挑选一个随机文本存储在一个编号的变量像这样

source1 = '''First text'''

source2 = '''Second text'''     
randomtext = source[randint(1,2)]
liste_source = randomtext.rstrip('\n\r').split(" ")

但是,它返回一个错误消息,说源没有定义。。。我不明白,因为source1和source2是在上面定义的。。。你知道吗


Tags: text文本source定义编号firstsplitsecond
3条回答

不要使用多个变量,而是使用一个列表:

source = [
    'First text',
    'Second text'
]

randomtext = source[randint(len(source))]

也可以改用^{}

randomtext = random.choice(source)

使用修改的代码:

import random
source1 = '''First text'''

source2 = '''Second text'''     
randomtext = eval("source"+str(random.randint(1,2)))

liste_source = randomtext.rstrip('\n\r').split(" ")

请改为:

source1 = "First text"
source2 = "Second text"    
randomtext = random.choice([source1, source2])
liste_source = randomtext.rstrip('\n\r').split(" ")

或者更简单:

sources = ["first text", "second text"]
randomtext = random.choice(sources)
liste_source = randomtext.rstrip('\n\r').split(" ")

相关问题 更多 >