user3032903 user3032903 - 2 months ago 9x
Python Question

Python eval a string representing dictionary containing network path (backslashes), weird behavior or expected?

I am trying to eval a string that represents a dictionary and I am not sure why the eval is producing result that looks incorrect to me unless there is something I am missing.

Here is the eval

>>> a = "{'a':'\\\\my_host\\my_path'}"
>>> a
>>> eval(a)
{'a': '\\my_host\\my_path'}

The processing of the backslash characters by the eval looks incorrect. The 4 backslashes before my_host are converted into 2 backslashes. But the 2 backslashes before my_path is still 2 backslashes.

What am I missing here? How can I properly eval a string representing dictionary where the values represent a network path?



You need to provide one more backslash, like this -

a = "{'a':'\\\\\my_host\\my_path'}"

This is because in \\\\m 1st \ from left gets consumed in escaping the \ after it. Hence to protect the first backslash, we need to add one more before that.

or if you don't want all this fuss you can use r for raw string, like -

a = "{'a':r'\\\\my_host\\my_path'}"

This won't consider any character as special.

>>> a =  "{'a':r'\\\\my_host\\my_path'}"
>>> eval(a)
{'a': '\\\\my_host\\my_path'}
>>> a =  "{'a':'\\\\\my_host\\my_path'}"
>>> eval(a)
{'a': '\\\\my_host\\my_path'}