I'm trying to condense this code:
cleaned = stringwithslashes
cleaned = cleaned.replace("\\n", "\n)
cleaned = cleaned.replace("\\r", "\n)
cleaned = cleaned.replace("\\", "")
I'm trying to condense this code:
cleaned = stringwithslashes
cleaned = cleaned.replace("\\n", "\n)
cleaned = cleaned.replace("\\r", "\n)
cleaned = cleaned.replace("\\", "")
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?
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.
Not totally sure this is what you want, but..
cleaned = stringwithslashes.decode('string_escape')
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)