简体   繁体   中英

How to encode and decode paths in python?

here is the problem, I want to dump and load windows paths in python under a unix system:

a = {"c":"a\b"}
b = json.dumps(a)
json.loads(b)
{u'c': u'a\x08'}

So, where did I go wrong?

You failed to remember that the backslash character in a string literal can introduce an escpae sequence. "\\b" represents the one-character string containing only a backspace.

The '\\' us being used for escaping b here. You can use "a\\\\b" or r"a\\b" to avoid this problem.

a = {"c":"a\\b"} # or a = {"c":r"a\b"}
b = json.dumps(a)
print json.loads(b)['c']

output

a\b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM