f-string e 逻辑运算符 OR?

f-string e Logical Operators OR?

我有一个非常简单的问题,我从没想过会遇到 or 运算符和 f 字符串。问题是 phrase_1_random 随机变量之一总是被打印出来。虽然从不打印 phrase_2_random 。我做错了什么?

我不需要同时打印它们

我想打印 phrase_1_random 或 phrase_2_random,但永远不会打印 X、Y 或 Z

import random

text_1 = ("A", "B", "C")
text_2 = ("X", "Y", "Z")

phrase_1_random = random.choice(text_1)
phrase_2_random = random.choice(text_2)

result= f"{phrase_1_random}" or "{phrase_2_random}"
#or f"{phrase_1_random}" or f"{phrase_2_random}"
print(result)

它正在做它应该做的事情。 这是 (w3schools) 的摘录:

Python considers empty strings as having a boolean value of the ‘false’ and non-empty strings as having a boolean value of ‘true’. For the ‘and’ operator if the left value is true, then the right value is checked and returned. If the left value is false, then it is returned For the ‘or’ operator if the left value is true, then it is returned, otherwise, if the left value is false, then the right value is returned.

因为短语 1 总是有一个值,所以它总是会被打印出来。

尝试

import random

text_1 = ("A", "B", "C")
text_2 = ("X", "Y", "Z")

phrase_1_random = random.choice(text_1)
phrase_2_random = random.choice(text_2)

result= [f"{phrase_1_random}", f"{phrase_2_random}"]
print(random.choice(result))

或更紧凑

import random

chars = ['A', 'B', 'C', 'X', 'Y', 'Z']
print(random.choice(chars))

听起来您希望 or 运算符执行某种随机选择 phrase_1_randomphrase_2_random,但这不是 [=12] =] 运算符。

or 运算符的作用

当您在上面提供的语法中使用 or 运算符时,它将从左到右计算赋值运算符 (=) 右侧的值。第一个“truthy”值(在本例中,第一个值是 non-empty 字符串)将用于赋值。

示例:

a = ""
b = "B"
thing = a or b   # thing will be "B"

x = "X"
y = "Y"
thing2 = x or y    # thing2 will be "X"

你可能想要什么

如果您想从 phrase_1_randomphrase_2_random 中进行某种随机选择,您也可以使用 random 库:

result= random.choice([phrase_1_random, phrase_2_random])