代码之家  ›  专栏  ›  技术社区  ›  Matt

Python版PHP的stripslashes

  •  11
  • Matt  · 技术社区  · 17 年前

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

    我怎样才能浓缩呢?

    5 回复  |  直到 10 年前
        1
  •  13
  •   dbr    17 年前

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

    cleaned = stringwithslashes.decode('string_escape')
    
        2
  •  3
  •   Greg Hewgill    17 年前

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

    import re
    def stripslashes(s):
        r = re.sub(r"\\(n|r)", "\n", s)
        r = re.sub(r"\\", "", r)
        return r
    cleaned = stripslashes(stringwithslashes)
    
        3
  •  1
  •   Jorgesys    11 年前

    decode('string_escape')

    cleaned = stringwithslashes.decode('string_escape')
    

    使用

    字符串\u转义 :在Python源代码中生成适合作为字符串文字的字符串

    cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n")
    
        4
  •  0
  •   Brad Wilson    17 年前

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

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

    那就是你想要的吗?或者你希望有更简洁的东西?

        5
  •  -4
  •   eplawless    17 年前

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

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

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

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

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

    总之,该死的,蟒蛇。