在python中,如何使用`or`运算符在两个字符串之间随机选择?

2024-05-15 13:54:19 发布

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

我和or操作员有问题。我刚开始学习Python。我应该在文本框中打印A或B。不能。问题是,只有A.B不打印。我该怎么办?多谢各位

A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
        
text.insert(tk.END, A or B)

Tags: oroftextnameanonareache
2条回答

您似乎想随机选择显示AB。您可以使用预安装的random模块完成此操作random.choice接受一个列表并从该列表中随机返回一个元素,这是所需的行为

import random

A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
        
text.insert(tk.END, random.choice([A, B]))

如果您想使用random.choice的更安全版本,可以使用预安装的^{} module

import secrets

A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
        
text.insert(tk.END, secrets.choice([A, B]))

您需要创建一个if语句来决定应该在什么条件下打印A或B。 或者实际上与布尔语一起使用。如果其中一个布尔值为true,or将返回true

相关问题 更多 >