Using “and” and “or” operator with Python strings [duplicate]

断了今生、忘了曾经 提交于 2019-11-26 07:41:02

问题


I don\'t understand the meaning of the line:

parameter and (\" \" + parameter) or \"\"

where parameter is string

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


回答1:


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 ""

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

  • a and b returns b if a is True, else returns a.
  • a or b returns a if a is True, else returns 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 - A1 is evaluated to True:

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

    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 B form expression for conditional expression. So, you should better use:

" " + parameter if parameter else ""

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




回答2:


Python considers empty strings as having boolean value of "false" and non-empty strings as having boolean value of "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:

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

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

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

ouput: test

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

output:(empty string)




回答3:


Empty string in Python is equivalent of a False boolean 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:

  • for a and b if a is False then b won't be evaluated
  • for a or b if a is True then b won't be evaluated
  • the value of a logical clause is the value of its most recently evaluated expression

If parameter evaluates to True the second part of the and clause will get evaluated: (" " + parameter). So it will add leading space to a parameter if it's not an empty string. The second part of the or clause won't get evaluated, as you can already tell the whole expression is True (True or anything is always True).

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

You can write it in a more verbose way:

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



回答4:


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

$ 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'



回答5:


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

Note that and and or evaluate to the first value that made them "succeed" or "fail" - and this need not be True or 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 works because the operators need not return True or False - it will be either the value of a or b.




回答6:


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)

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



来源:https://stackoverflow.com/questions/19213535/using-and-and-or-operator-with-python-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!