2

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"

Can someone clarify this?

0

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

json.dumps is used to convert dictonaries to json strings. In other words, it interprets the import and creates the equivalent of it as a json. What that means is, that puting a single string in will result in it being transformed to the json equivalent of a single string.

hello = json.dumps("hello")
print(hello)
 => "hello"

In the json-format, strings are in quotes, which is why json.dumps() puts it in quotes.

Comments

-4
print(json.dumps('hello'))

output -> "hello"

print('hello')

output -> hello

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.