【问题标题】:How do I randomly select between two strings with the `or` operator in python?如何在 python 中使用“或”运算符在两个字符串之间随机选择?
【发布时间】:2021-09-01 21:22:36
【问题描述】:

我对 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)

【问题讨论】:

  • 你想让它随机插入吗?
  • 你想要随机性吗?它只会打印B is A is an empty string
  • 这能回答你的问题吗? How to randomly select an item from a list?
  • @Samathingamajig 我想是的。因为该链接还谈到了secure_random = random.SystemRandom()?这是什么意思?
  • 它似乎是一个更好的随机数生成器,但对于像这样简单的事情不需要它(可能更慢且对系统要求更高)。在此处了解更多信息:docs.python.org/3.6/library/secrets.html#module-secrets

标签: python python-3.x python-2.7 tkinter


【解决方案1】:

您似乎想随机选择显示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 版本,可以使用预装的secrets 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]))

【讨论】:

  • @Samanthingamajic 完美。谢谢。我不知道随机模块
【解决方案2】:

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

【讨论】:

  • 不完全是。 or||的python版本实际上返回了第一个真值。看这里的例子:wandbox.org/permlink/zqNl4LfeK8KeS4cf(未来读者的源代码:print("" or "Hello, World"); print(5 or 6); print(0 or 6); print(False or None); print(None or "Hello")
  • 哇,我不知道它也可以这样使用..谢谢你的信息!
猜你喜欢
  • 2014-01-30
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 2012-02-03
  • 2012-05-19
  • 2020-03-27
  • 1970-01-01
  • 2013-12-31
相关资源
最近更新 更多