I've updated my answer for clarity.
If the string comes directly from an API then it should already be in a raw format (or the rawest that will be accessible to you), such as r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
. Therefore, Python won't be assuming escaped characters and there shouldn't be an issue.
To answer your other question about raw strings - to print a string as a raw string in Python try the repr
function, which returns a printable representational string of the given object.
query = "$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))
Here is the output:
'$\\displaystyle \x08inom n r = \\dfrac{n!}{r!(n-r)!}$'
Note that in the true raw data of query
above, the \b
character is still technically stored as the \b
encoding (or \x08
), not as two separate characters. Why isn't \d
stored as an encoding, you may ask? Because \d
is not a valid encoded escape sequence, so it is overlooked and Python treats the \
as a character. (Ahh... silently ignoring parsing errors, isn't this why we love Python?)
Then what about this example?
query = r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))
Looks good, but wait, Python prints '$\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$'
.
Why the \\
? Well, the repr
function returns a printable representational string of the given object, so to avoid any confusion the \
character is properly escaped with \
, creating \\
.
All of that coming full circle and back to your question - if the value of a string comes directly from an API call, then the string data should already be translated from a binary encoding and things like escape sequences shouldn't be an issue (because the aren't in the raw data). But in the example you provided you declared a string in a query = "st\ring"
format, which unfortunately isn't equivalent to retrieving a string from an API, and the obvious solution would be to use the query = r"st\ring"
format.