So I'm using yaml for some configuration files and py yaml to parse it. For one field I have something like:
host: HOSTNAME\SERVER,5858
But when it gets parsed here what I get:
{
"host": "HOSTNAME\\SERVER,5858"
}
With 2 backslashes. I tried every combination of single quotes, double quotes, etc. What's the best way to parse it correctly ? Thanks
In YAML, text scalars can be surrounded by quotes enabling escape sequences such as \n to represent a new line, \t to represent a tab, and \\ to represent the backslash.
In double quoted strings if you need to include a literal double quote in your string you can escape it by prefixing it with a backslash \ (which you can in turn escape by itself). In single quoted strings the single quote character can be escaped by prefixing it with another single quote, basically doubling it.
If you use the backslash character and the target system is a Microsoft Windows system, the YAML-to-JSON parser inserts a second backslash character as an escape character. If the escaped backslash character (\\) is combined with a newline character (\n), the YAML code cannot be processed by the parser.
When double quotes, "...." , go around a scalar string you use backslash ( \ ) for escaping, and you have to escape at least the backslash and the double quotes. In addition you can escape other special characters like linefeed ( \n ) and escape an end-of-line by preceding it by a backslash.
len("\\") == 1
. What you see is the representation of the string as Python string literal. Backslash has special meaning in a Python literal e.g., "\n"
is a single character (a newline). To get literal backslash in a string, it should be escaped "\\"
.
You aren't getting two backslashes. Python is displaying the single backslash as \\
so that you don't think you've actually got a \S
character (which doesn't exist... but e.g. \n
does, and Python is trying to be as unambiguous as possible) in your string. Here's proof:
>>> data = {"host": "HOSTNAME\\SERVER,5858"}
>>> print(data["host"])
HOSTNAME\SERVER,5858
>>>
For more background, check out the documentation for repr()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With