What is the output of print exception and why doesn't it match the string outputed

Viewed 46

In the following block of code:

dictionary = dict()
dictionary[0] = {}
        
try:
    print(dictionary[0]["tomato"])

except Exception as e:
    print(e)          # prints 'tomato'
    print(str(e))     # prints 'tomato'
    
    if str(e) == 'tomato':
        print("Not tomato")     # never prints, why?

Even though print(e) prints 'tomato', str(e) == 'tomato' is not True
Can someone please explain how can this be?

1 Answers

Those first two print statements print 'tomato' including the single quotes, so that means the quotes are literally part of the string.

Change your if statement to this:

if str(e) == "'tomato'":
Related