0

In the Python3 tutorials, it is stated that "It is possible to assign the result of a comparison or other Boolean expression to a variable." The example given is:

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

What exactly does the 'or' operator do when comparing strings? Why is 'Trondheim' chosen?

uncreative
  • 341
  • 5
  • 11

4 Answers4

2

Inclusive or selects the first non-falsy string (checking from left to right), which in this case is 'Trondheim'

>>> bool('')
False
>>> bool('Trondheim')
True

It is sometimes preferable when performing this type of check to strip the string literals as a blank space is also truthy, if you intend to not select whitespaces.

>>> bool(' ')
True
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

In the assignment of non_null, the or comparisons are evaluated sequentially, which translates to this :

if string1:
    non_null = string1
elif string2:
    non_null = string2
elif string3:
    non_null = string3
else:
    non_null = False

However, in your example, string1 is an empty string, which is evaluated as False (you can check this by typing if not '':print("Empty") in your prompt).

Since string2 is not empty, hence evaluated as True, it is assigned to non_null, hence the result.

3kt
  • 2,543
  • 1
  • 17
  • 29
1

or returns the value on the left of it if that is true-ish, and the one on the right otherwise.

For strings, only "" (the empty string) is not true-ish, and all others are.

So

>>> "" or "Test"
"Test"

and

>>> "One" or "Two"
"One"

It doesn't do a comparison at all.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

When treated as boolean, an empty string will return False and a non empty string will return True.

Since Python supports short circuiting, in the expression a or b, b won't be evaluated if a is True.

In your example, we have '' or 'Trondheim' or 'Hammer Dance'.

This expression is evaluated from left to right, so the first thing being evaluated is '' or 'Trondheim', or in other words False or True, which returns True. Next, Python tries to evaluate 'Trondheim' or 'Hammer Dance' which in turn becomes True or 'Hammer Dance'. Because of the short circuiting mentioned earlier, because the left object is True, 'Hammer Dance' doesn't even gets evaluated to True, which is why 'Trondheim' is returned.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154