使用“和"和“或"带有 Python 字符串的运算符 [英] Using "and" and "or" operator with Python strings

查看:47
本文介绍了使用“和"和“或"带有 Python 字符串的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这行的意思:

parameter and (" " + parameter) or ""

其中参数是字符串

通常情况下,为什么要对 Python 字符串使用 andor 运算符?

Why would one want to use and and or operator, in general, with python strings?

推荐答案

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

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?

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

这就是这个表达式所做的.首先,您应该了解 andor 运算符的作用:

This is what that expression is doing. First you should understand what and and or operator does:

  • a 和 b 返回 b 如果 a 是 True,否则返回 a.
  • a or b 如果 a 是 True,则返回 a,否则返回 b.
  • a and b returns b if a is True, else returns a.
  • a or b returns a if a is True, else returns b.

所以,你的表情:

parameter and (" " + parameter) or ""

实际上等效于:

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

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

How the expression is evaluated if:

  • 参数 - A1 被评估为 True:

  • parameter - A1 is evaluated to True:

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

result = (" " + parameter) or ""

result = " " + parameter

  • 参数 - A1None:

  • parameter - A1 is None:

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

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

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

    " " + parameter if parameter else ""
    

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

    instead of the given expression. See PEP 308 - Conditional Expression for motivation behind the if-else expression.

    这篇关于使用“和"和“或"带有 Python 字符串的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆