Skip to main content
 首页 » 编程设计

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

2024年11月24日23dyllove98

所以我试图从列表中随机选择一个字符串,并在字符串中的任意位置包含一个变量。

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

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

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

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

请您参考如下方法:

您不小心使用 , 而不是像在第一个元素中那样使用 + 将最后两个元素变成元组。

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.")] 

您还可以通过使用字符串格式来简化 markthings 的实例化,例如 f-strings

markthings = [f"{test} went to the store.", f"{test} wants to die.", f"At the store, {test} was being a idiot."]