Differences Between Python Single Quotation and Embedded Function str()

Asked 1 years ago, Updated 1 years ago, 430 views

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

2022-10-08 01:01

2 Answers

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.

If you look at the execution results, you can see that the string changes depending on whether it is shaped or not.

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


2022-10-08 01:01

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


2022-10-08 01:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.