对于静态字符串,将r
放在字符串前面会得到原始字符串(例如r'some \' string'
)。由于不可能将r
放在unicode字符串变量的前面,将字符串变量动态转换为其原始格式的最小方法是什么?是否应将所有反斜杠手动替换为双反斜杠?
str_var = u"some text with escapes e.g. \( \' \)"
raw_str_var = ???
python大神给出的解决方案
如果您确实需要转义一个字符串,假设您想将换行符打印为\n
,则可以将encode
方法与Python特定的string_escape
编码一起使用:
>>> s = "hello\nworld"
>>> e = s.encode("string_escape")
>>> e
"hello\\nworld"
>>> print s
hello
world
>>> print e
hello\nworld
您没有提及任何有关unicode的信息,也没有提及使用的是哪个Python版本,但如果要处理unicode字符串,则应改用unicode_escape
。
>>> u = u"föö\nbär"
>>> print u
föö
bär
>>> print u.encode('unicode_escape')
f\xf6\xf6\nb\xe4r
您的帖子最初带有regex标签,也许re.escape
是您真正要查找的内容?
>>> re.escape(u"foo\nbar\'baz")
u"foo\\\nbar\\'baz"
不是“两次转义”,即打印上面的字符串会产生:
foo\
bar\'baz