tags:

views:

1024

answers:

5

I'm trying to condense this code:

cleaned = stringwithslashes
cleaned = cleaned.replace("\\n", "\n)
cleaned = cleaned.replace("\\r", "\n)
cleaned = cleaned.replace("\\", "")
A: 

You can obviously concatenate everything together:

cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","")

Is that what you were after? Or were you hoping for something more terse?

Brad Wilson
A: 

I started with the concatenated version. What I have works fine in, just wondering if there is a library function that handles this sort of thing and is more thorough.

Specifically, the text in stringwithslashes has been run throught MYSQLdb.escape_string()

A: 

Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.

Regular expressions to the rescue (code not tested):

p = re.compile( '\\(\\\S)')
p.sub('\1',escapedstring)

In theory that takes anything of the form \\(not whitespace) and returns \(same char)

edit: Upon further inspection, Python regular expressions are broken as all hell;

>>> escapedstring
'This is a \\n\\n\\n test'
>>> p = re.compile( r'\\(\S)' )
>>> p.sub(r"\1",escapedstring)
'This is a nnn test'
>>> p.sub(r"\\1",escapedstring)
'This is a \\1\\1\\1 test'
>>> p.sub(r"\\\1",escapedstring)
'This is a \\n\\n\\n test'
>>> p.sub(r"\(\1)",escapedstring)
'This is a \\(n)\\(n)\\(n) test'

In conclusion, what the hell, Python.

eplawless
+3  A: 

Not totally sure this is what you want, but..

cleaned = stringwithslashes.decode('string_escape')
dbr
A: 

It sounds like what you want could be reasonably efficiently handled through regular expressions:

import re
def stripslashes(s):
    r = re.sub(r"\\(n|r)", "\n", s)
    r = re.sub(r"\\", "", r)
    return r
cleaned = stripslashes(stringwithslashes)
Greg Hewgill