Using decode() vs. regex to unescape this string

萝らか妹 提交于 2019-12-07 01:46:57

问题


I have the following string and I'm trying to figure out the best practice for unescaping it.

The solution has to be somewhat flexible in that I'm receiving this input from an API and I can't be absolutely certain that the current character structure (\n as opposed to \r) will always be the same.

'"If it ain\'t broke, don\'t fix it." \nWent in for a detailed car wash.\nThe attendants raved-up my engine when taking the car into the tunnel. NOTE: my car is...'

This regex seems like it should work:

text_excerpt = re.sub(r'[\s"\\]', ' ', raw_text_excerpt).strip()

I've aso read that decode() might work (and would be a better solution generally).

raw_text_excerpt.decode('string_unescape')

Tried something along those lines and it didn't work. Any suggestions? Is regex best here?


回答1:


The codec you're looking for is string-escape:

>>> print "\\'".decode("string-escape")
'

I'm not sure what version they added it in, though... could be an older version you're using that doesn't have it. I'm running:

Python 2.6.6 (r266:84292, Mar 25 2011, 19:36:32) 
[GCC 4.5.2] on linux2


来源:https://stackoverflow.com/questions/10268918/using-decode-vs-regex-to-unescape-this-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!