Python版本的PHP';条纹斜杠

Python版本的PHP';条纹斜杠,python,string,escaping,Python,String,Escaping,我编写了一段代码,将PHP的条带斜杠转换为有效的Python[反斜杠]转义: cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') 我怎样才能浓缩它 您显然可以将所有内容连接在一起: cleaned = stringwithslashes.replace("\\n",

我编写了一段代码,将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有一个内置的escape()函数,类似于PHP的addslashes,但没有unescape()函数(stripslashes),这在我看来有点可笑

要拯救的正则表达式(未测试代码):

理论上,它接受任何形式的\(不是空格)并返回\(相同字符)

编辑:经过进一步检查,Python正则表达式完全崩溃了

>>> 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'

总之,这到底是怎么回事,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)
使用
解码('string\u escape')

使用

string\u escape:生成一个适合在Python源代码中用作字符串文字的字符串

或者像Wilson的答案一样连接replace()

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