13

I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:

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

How can I condense it?

6 Answers 6

13

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

cleaned = stringwithslashes.decode('string_escape')
0
3

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)
1

use decode('string_escape')

cleaned = stringwithslashes.decode('string_escape')

Using

string_escape : Produce a string that is suitable as string literal in Python source code

or concatenate the replace() like Wilson´s answer.

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

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?

0

This function did the job. One can not simply remove all the backslashes. Only specific sequences can be removed that are added by PHP addslashes.

def stripslashes(t: bytes):
    return t.replace(b'\\\\', b'\\').replace(b'\\\'', b'\'').replace(b'\\"', b'"').replace(b'\\0', b'\0')

To make it work for strings, just remove all "b" and "bytes".

-4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.