Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backslash in Yaml string [duplicate]

Tags:

python

yaml

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

like image 459
remiH Avatar asked Feb 08 '13 18:02

remiH


People also ask

How do you do a backslash in YAML?

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.

How do you escape double quotes in YAML?

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.

What is Slash in YAML?

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.

How do you escape special characters in YAML file?

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.


2 Answers

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 "\\".

like image 91
jfs Avatar answered Oct 20 '22 14:10

jfs


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

like image 25
Zero Piraeus Avatar answered Oct 20 '22 15:10

Zero Piraeus