Python version of PHP's stripslashes

风流意气都作罢 提交于 2019-12-30 06:04:28

问题


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?


回答1:


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

cleaned = stringwithslashes.decode('string_escape')



回答2:


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)



回答3:


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?




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/13454/python-version-of-phps-stripslashes

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