Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are these two strings not equal in Python?

I have a simple python code sample

import json
hello = json.dumps("hello")
print(type(hello))

if hello == "hello":
    print("They are equal")
else:
    print("They are not equal")

This is evaluating to "They are not equal". I don’t understand why these values are not equal.

I’m re-familiarizing myself with Python but I read that this "==" can be used as an operator to compare strings in Python. I also printed the type of hello which evaluates to "str"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone clarify this?

>Solution :

The behavior becomes much more clear once you print out the result from json.dumps():

print("hello", len("hello"))
print(hello, len(hello))

This outputs:

hello 5
"hello" 7

json.dumps() adds extra quotation marks — you can see that the lengths of the two strings aren’t the same. This is why your check fails.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading