Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
"{'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.

like image 482
user3032903 Avatar asked May 25 '26 06:05

user3032903


1 Answers

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'}
like image 108
theharshest Avatar answered May 30 '26 18:05

theharshest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!