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?
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
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