PHP 的 stripslashes 的 Python 版本

Python version of PHP's stripslashes

提问人: 提问时间:8/17/2008 最后编辑:ʇsәɹoɈ 更新时间:5/31/2015 访问量:8800

问:

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

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

我怎样才能压缩它?

Python 字符串 转义

评论


答:

0赞 Brad Wilson 8/17/2008 #1

显然,您可以将所有内容连接在一起:

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

这就是你所追求的吗?或者你希望更简洁的东西?

-4赞 eplawless 8/17/2008 #2

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

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

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

从理论上讲,它采用 \\(不是空格)形式并返回 \(相同的字符)

编辑:经过进一步检查,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。

13赞 dbr 8/17/2008 #3

不完全确定这是你想要的,但是..

cleaned = stringwithslashes.decode('string_escape')
3赞 Greg Hewgill 8/17/2008 #4

听起来你想要的东西可以通过正则表达式合理有效地处理:

import re
def stripslashes(s):
    r = re.sub(r"\\(n|r)", "\n", s)
    r = re.sub(r"\\", "", r)
    return r
cleaned = stripslashes(stringwithslashes)
1赞 Jorgesys 2/19/2014 #5

decode('string_escape')

cleaned = stringwithslashes.decode('string_escape')

string_escape :在Python源代码中生成适合作为字符串文字的字符串

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

cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n")
0赞 Cuchac 11/29/2023 #6

这个功能完成了工作。不能简单地删除所有反斜杠。只能删除由 PHP 添加斜杠添加的特定序列。

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

要使其适用于字符串,只需删除所有“b”和“bytes”。