Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decode() vs. regex to unescape this string

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?

like image 916
Ben Avatar asked Apr 22 '12 14:04

Ben


1 Answers

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
like image 192
javawizard Avatar answered Nov 03 '22 05:11

javawizard