I would like to know the difference between Python single quotation and built-in function str().
s1='{"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone"]}'
s2=str({"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone"]}})
s1 == s2
->False
So why is that so?
python string
The former (s1
) is a single quotation that simply declares a string no matter what it is inside.
The latter (s2
) has once created an dict
object and stringed it with the function.
Because the latter process involves type conversion from dict
to str
, s1
and s2
are no longer identical strings because the type conversion involves shaping.
Try executing the code below.
s1='{"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone"]}'
s2=str({"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone"]}})
print(s1==s2)# False
print(s1)#{"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone" ]}}
print(s2)#{'input':{'action':'read','role':'User','request':['gender','address','birthDate','familyName','telephone']}}
print(s1==s2.replace(", "", ").replace("", "")#True
If you look at the execution results, you can see that the string changes depending on whether it is shaped or not.
False
{"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone" ]}}
{'input': {'action': 'read', 'role': 'User', 'request': ['gender', 'address', 'birthDate', 'familyName', 'telephone']}}
True
Also, you can read the specifications from 3.1.2. String type (string) in the official documentation to see why kukuri characters are replaced with single quotation when shaped.
When an interactive interpreter prints a string, the output string is enclosed in quotation marks and the special characters are escaped with a backslash.Sometimes the output characters look different from the input (the quotation marks surrounding them change), but the two strings are the same.If the string contains single quotes and does not contain double quotes, it is enclosed in double quotes, otherwise it is enclosed in single quotes.
References
s2 is a dictionary string representation.
If other encoding errors are given, str(object) returns type(object).str(object), which is the "informal" or "nicely printable string presentation of object.
[Quote] embedded --- Python 3 document
Therefore, the contents of the dictionary are slightly shaped and printed.
Here's probably the input/output you'll expect.
>>s1="{'input':{'action':'read', 'role':'User', 'request':['gender', 'address', 'birthDate', 'familyName', 'telephone']}}"
>>s2=str({"input":{"action":"read", "role":"User", "request":["gender", "address", "birthDate", "familyName", "telephone"]}})
>>>s1 == s2
True
© 2025 OneMinuteCode. All rights reserved.