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)
).