gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:21 25 4
gpt4 key购买 nike

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

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

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

关于python - 从列表中随机选择时如何在字符串中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57022717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com