When I create a string containing backslashes, they get duplicated:
NOTE : I want to add \
in request because i want to call third party API and they want me to send request with \
in some of their keys.
I have taken reference from this answer
CodePudding user response:
mystr
isn't a str
, it's a dict
. When you print a dict
, it prints the repr
of each string inside it, rather than the string itself.
>>> mydict = {"str": "why\does\it\happen?"}
>>> print(mydict)
{'str': 'why\\does\\it\\happen?'}
>>> print(repr(mydict['str']))
'why\\does\\it\\happen?'
>>> print(mydict['str'])
why\does\it\happen?
Note that the repr()
includes elements other than the string contents:
- The quotes around it (indicating that it's a string)
- The contents use backslash-escapes to disambiguate the individual characters. This extends to other "special" characters as well; for example, if this were a multiline string, the
repr
would show linebreaks as\n
within a single line of text. Actual backslash characters are always rendered as\\
so that they can be distinguished from backslashes that are part of other escape sequences.
The key thing to understand is that these extra elements are just the way that the dict is rendered when it is printed. The actual contents of the string inside the dict do not have "doubled backslashes", as you can see when you print mydict['str']
.
If you are using this dict to call an API, you should not be using str(mydict)
or anything similar; if it's a Python API, you should be able to use mydict
itself, and if it's a web API, it should be using something like JSON encoding (json.dumps(mydict)
).
CodePudding user response:
I think that to build the printed string of the dict, python call the __repr__
method of object inside it (for the values) instead of the __str__
as you would expect for printing the dict.
It would make sense since dict can contain every type of object not just string so the __repr__|
method can be found everywhere (it's included in the base object in python) when the __str__
need to be written.
But it's only a guess, not a definitive answer.