带有编号变量的随机文本

Random text with numbered variables

我目前正在尝试选择存储在这样的编号变量中的随机文本

source1 = '''First text'''

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

然而,它returns给我一条错误消息,说源未定义...我不明白,因为上面定义了 source1 和 source2...

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

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

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

您也可以使用 random.choice 代替:

randomtext = random.choice(source)

改为这样做:

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(" ")

使用修改后的代码:

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

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

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