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
>Solution :
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)