Search code examples
pythonstringboolean-expression

How to use parentheses correctly?


Why does it work differently?

p='/content/Images_of_Waste/img/PET968.txt'
p[-3:]!='txt' and p[-3:]!='jpg'
False
p[-3:]!=('txt' and 'jpg')
True

How can I use parentheses correctly?


Solution

  • In Python, non-empty strings are effectively True.

    That is to say,

    if 'txt':
        # this code will execute
    

    As the @gimix mentions below, however,

    if 'txt' == True:
        # this code will not execute
    

    In terms of ('txt' and 'jpg'), 'txt' is not False, and neither is 'jpg', thus, ('txt' and 'jpg') evaluates to 'jpg' per @Manish's comment.