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
"{'a':'\\\\my_host\\my_path'}"
>>> 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?
Thanks.
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'}
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