从列表中随机选择时,如何在字符串中使用变量?

时间:2019-07-13 20:48:17

标签: python python-3.x python-3.7

因此,我尝试从列表中随机选择一个字符串,并在该字符串的任何位置包括一个变量。

我已经尝试将字符串和变量括在括号和单引号中,而这两个没有用。

test = "mark"

markthings = [(test + "went to the store."), (test, "wants to die."), ("At the store, ", test, " was being a idiot.")]

print(random.choice(markthings))

我希望它打印出类似“在商店里,马克是个白痴。”

相反,我得到了“('在商店里','马克','是个白痴。)

2 个答案:

答案 0 :(得分:1)

您不小心像使用第一个元素那样,对连接的字符串使用,而不是+将最后两个元素变成元组。

In [23]: test = "mark" 
    ...: markthings = [(test + "went to the store."), (test, "wants to die."), ("At the store, ", te
    ...: st, " was being a idiot.")]                                                                

In [24]: [type(item) for item in markthings]                                                        
Out[24]: [str, tuple, tuple]

一旦您相应地更改markthings以使每个元素成为字符串,它将按预期工作

markthings = [(test + "went to the store."), (test+ "wants to die."), ("At the store, "+ test+ " was being a idiot.")]

您还可以通过使用字符串格式(例如f-strings

)来简化markthings的实例化
markthings = [f"{test} went to the store.", f"{test} wants to die.", f"At the store, {test} was being a idiot."]

答案 1 :(得分:0)

尝试一下

import random
test = "mark"

markthings = [(test, "went to the store."), (test, "wants to die."), ("At the store, ", test, " was being a idiot.")]

print(" ".join(random.choice(markthings)))