对 Python 字符串使用“and”和“or”运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19213535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:09:51  来源:igfitidea点击:

Using "and" and "or" operator with Python strings

pythonstringboolean-operations

提问by rok

I don't understand the meaning of the line:

我不明白这行的意思:

parameter and (" " + parameter) or ""

where parameteris string

其中参数是字符串

Why would one want to use andand oroperator, in general, with python strings?

一般来说,为什么要使用andandor运算符和 python 字符串?

采纳答案by Rohit Jain

Suppose you are using the value of parameter, but if the value is say None, then you would rather like to have an empty string ""instead of None. What would you do in general?

假设您正在使用 的值parameter,但如果该值是 say None,那么您宁愿使用空字符串""而不是None。你一般会怎么做?

if parameter:
    # use parameter (well your expression using `" " + parameter` in this case
else:
    # use ""

This is what that expression is doing. First you should understand what andand oroperator does:

这就是那个表达式正在做的事情。首先,您应该了解andandor运算符的作用:

  • a and breturns bif a is True, else returns a.
  • a or breturns aif a is True, else returns b.
  • a and b返回b如果是True,否则返回a
  • a or b返回a如果是True,否则返回b

So, your expression:

所以,你的表达:

parameter and (" " + parameter) or ""

which is effectively equivalent to:

这实际上相当于:

(parameter and (" " + parameter)) or  ""
#    A1               A2               B
#           A                     or   B

How the expression is evaluated if:

在以下情况下如何评估表达式:

  • parameter - A1is evaluated to True:

    result = (True and " " + parameter) or ""
    
    result = (" " + parameter) or ""
    
    result = " " + parameter
    
  • parameter - A1is None:

    result = (None and " " + parameter) or ""
    
    result = None or ""
    
    result = ""
    
  • parameter - A1被评估为True

    result = (True and " " + parameter) or ""
    
    result = (" " + parameter) or ""
    
    result = " " + parameter
    
  • parameter - A1None

    result = (None and " " + parameter) or ""
    
    result = None or ""
    
    result = ""
    


As a general suggestion, it's better and more readable to use A if C else Bform expression for conditional expression. So, you should better use:

作为一般建议,将A if C else B表单表达式用于条件表达式会更好且更具可读性。所以,你应该更好地使用:

" " + parameter if parameter else ""

instead of the given expression. See PEP 308 - Conditional Expressionfor motivation behind the if-elseexpression.

而不是给定的表达式。有关表达式背后的动机,请参阅PEP 308 - 条件if-else表达式。

回答by Cfreak

It checks if parameterhas a value. If it does it prepends a space. If not it returns an empty string.

它检查是否parameter有值。如果是这样,它会在前面加上一个空格。如果不是,则返回一个空字符串。

$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 'bar'
>>> foo and (" " + foo) or ""
' bar'

回答by BartoszKP

Empty string in Python is equivalent of a Falseboolean value, the same way as an empty list. The line you've presented is Python version of a ternary operator (as noted in the comment below, nowadays an obsolete construction, as Python now has a real ternary operator). It is based on three rules:

Python 中的空字符串等效于False布尔值,与空列表的方式相同。您提供的行是三元运算符的 Python 版本(如下面的评论中所述,现在已经过时了,因为 Python现在有一个真正的三元运算符)。它基于三个规则:

  • for a and bif ais Falsethen bwon't be evaluated
  • for a or bif ais Truethen bwon't be evaluated
  • the value of a logical clause is the value of its most recently evaluated expression
  • 因为a and b如果aFalse然后b将不会被评估
  • 因为a or b如果aTrue然后b将不会被评估
  • 逻辑子句的值是其最近评估的表达式的值

If parameterevaluates to Truethe second part of the andclause will get evaluated: (" " + parameter). So it will add leading space to a parameterif it's not an empty string. The second part of the orclause won't get evaluated, as you can already tell the whole expression is True(Trueor anything is always True).

如果parameter对子句True的第二部分and求值将被求值:(" " + parameter)。因此,parameter如果它不是空字符串,它将向 a 添加前导空格。or子句的第二部分不会被评估,因为您已经可以知道整个表达式 is True(True或者任何东西 always True)。

If parameteris False(empty string in this context) the second part of the andclause won't get evaluated, as you can already tell it's being False(Falseand anything is always False). Therefore the second part of the orclause gets evaluated returning an empty string.

如果parameterFalse(在此上下文中为空字符串),and则不会评估该子句的第二部分,因为您已经知道它是FalseFalse并且任何东西总是False)。因此,or子句的第二部分被评估返回一个空字符串。

You can write it in a more verbose way:

您可以用更详细的方式编写它:

if parameter:
    return " " + parameter
else:
    return ""

回答by user2246674

Consider this TTL. Then it's just plugging in different scenarios to see what happens :)

考虑这个 TTL。然后它只是插入不同的场景,看看会发生什么:)

Note that andand orevaluate to the first value that made them "succeed" or "fail"- and this need not be True or False!

请注意,andor评估为使它们“成功”或“失败”的第一个值- 这不必是 True 或 False!

a    b    a or b   a and b
--   --   ------   ------- 
T    T    a (T)    b (T)
T    F    a (T)    b (F)
F    T    b (T)    a (F)
F    F    b (F)    a (F)

T and F represent "Truth-y" and "False-y" values. This expression-chaining worksbecause the operators need not return True or False - it will be either the value of aor b.

T 和 F 代表“真-y”和“假-y”值。这表达式链接的作品,因为运营商需要无法返回真或假-这将是任一值ab

回答by Pawel Bragoszewski

Python considers empty strings as having boolean value of "false" and non-empty strings as having boolean value of "true".

Python 将空字符串视为具有“false”的布尔值,将非空字符串视为具有“true”的布尔值。

So there're only two possible outcomes of the expression, i.e. for empty string and for non-empty string.

所以表达式只有两种可能的结果,即空字符串和非空字符串。

Second thing to notice is that which value of "or" and "and" operator are returned. Python does not return just true or false value, for strings and or/and operator it returns one of the strings (considering they have value of true or false). Python uses lazy approach:

要注意的第二件事是返回“or”和“and”运算符的哪个值。Python 不只返回 true 或 false 值,对于字符串和或/和运算符,它返回字符串之一(考虑到它们具有 true 或 false 值)。Python 使用惰性方法:

For "and" operator if left value is true, then right value is checked and returned. if left value is false, then it is returned

对于“and”运算符,如果左值为真,则检查并返回右值。如果左值为假,则返回

For "or" operator if first value is true, then it is returned. otherwise if second value is false, then second value is returned

对于“或”运算符,如果第一个值为真,则返回它。否则,如果第二个值为 false,则返回第二个值

parameter = 'test'
print( parameter and (" " + parameter) or "" )

ouput: test

输出:测试

parameter = ''
print( parameter and (" " + parameter) or "" )

output:(empty string)

输出:(空字符串)

回答by Zhenhua

With all the good answers, I found these statements help me remember this better and fit how my brain works (and hopefully for for some more out there) :

有了所有好的答案,我发现这些陈述可以帮助我更好地记住这一点并适合我的大脑工作方式(希望还有更多):

  • “and" returns the first False item (e.g., None, “”, [], (), {}, 0) or the last item if none (e.g. no False found)

  • “or" returns the first True item or the last item (e.g. no True found)

  • “and”返回第一个 False 项(例如,None、“​​”、[]、()、{}、0)或最后一项,如果没有(例如未找到 False)

  • “或”返回第一个 True 项目或最后一个项目(例如未找到 True)

In summary they all return the first item that decides the outcome of the statement. (In the worst case, the last item in the sequence)

总之,它们都返回决定语句结果的第一项。(在最坏的情况下,序列中的最后一项)

Note this rule also applies to a chained all "and" or all "or" statement

请注意,此规则也适用于链式全“和”或全“或”语句