0

From my understanding, and is a short-circuit operator as explained in the doc. But, why the part c gets printed every I run the code below?

My solution: if ('RB' in t) and (not ',' in t): ..., but what I want is an explanation.

test = '977'

if 'RB' and '+' in test:
    print('a')
    test = int(test.replace('RB+', '')) * 1000
elif ',' and 'RB' in test:
    print('b')
    temp_test = test.replace(',', '')
    test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' and not ',' in test:
    print('c')
    test = int(test.replace('RB', '')) * 1000
else:
    test = int(test)

print(test)

Ouput

c
977000
  • 1
    It's parsed as `if 'RB' and (not ',' in test):` – Barmar Nov 10 '21 at 21:27
  • "why the part c gets printed every I run the code below?". Because there's no comma in `test`. – kindall Nov 10 '21 at 21:28
  • All of your conditions are effectively ignoring `'RB'` because that's always truthy by itself. `if 'RB' and '+' in test:` is equivalent to `if '+' in test:` – Barmar Nov 10 '21 at 21:28
  • For example, in your first `if`, the expression `'RB'` is `truthy` all by itself, so it can be rewritten as: `if True and '+' in test:`, so the `True and` can be removed, leaving you with `if '+' in test:`. – quamrana Nov 10 '21 at 21:30

1 Answers1

1

Because you are effectively checking the 'truthiness' of the string 'RB, which is True. See: https://stackoverflow.com/questions/18491777/truth-value-of-a-string-in-python#:~:text=3%20Answers&text=Python%20will%20do%20its%20best,empty%20string%20is%20considered%20True%20.

Your third elif breaks down as:

elif ('RB') and (not ',' in test'):

You probably want:


if 'RB' in test and '+' in test:
    print('a')
    test = int(test.replace('RB+', '')) * 1000
elif ',' in test and 'RB' in test:
    print('b')
    temp_test = test.replace(',', '')
    test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' in test and not ',' in test:
    print('c')
    test = int(test.replace('RB', '')) * 1000
else:
    test = int(test)

print(test)
daddydan
  • 128
  • 7