Python version of PHP's stripslashes

与世无争的帅哥 提交于 2019-11-30 18:45:34

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)

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?

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!