Python版本的PHP的反斜杠

时间:2020-03-05 18:40:06  来源:igfitidea点击:

我编写了一段代码,将PHP的脱节转换为有效的Python [反斜杠]转义:

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

我如何凝结它?

解决方案

回答

我们显然可以将所有内容连接在一起:

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

那是你所追求的吗?还是我们希望更简洁?

回答

Python具有类似于PHP的addlashes的内置escape()函数,但是没有unescape()函数(stripslashes),在我看来,这有点荒谬。

救援的正则表达式(未经测试的代码):

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

从理论上讲,采取任何形式\(非空白)并返回(相同char)

编辑:经过进一步检查,Python正则表达式被打破了。

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

总之,Python,该死的。

回答

不能完全确定这是我们想要的,但是..

cleaned = stringwithslashes.decode('string_escape')

回答

听起来我们可以通过正则表达式合理地有效地处理所需的内容:

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