12

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

remiH
  • 131
  • 1
  • 1
  • 7

2 Answers2

8

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

jfs
  • 399,953
  • 195
  • 994
  • 1,670
5

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

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160