Python regex to replace double backslash with single backslash

前端 未结 2 1396
栀梦
栀梦 2020-12-11 07:57

I\'m trying to replace all double backslashes with just a single backslash. I want to replace \'class=\\\\\"highlight\' with \'class=\\\"highlight\'

相关标签:
2条回答
  • 2020-12-11 08:04

    You only got one backslash in string:

    >>> string = 'class=\\"highlight' 
    >>> print string
    class=\"highlight
    

    Now lets put another one in there

    >>> string = 'class=\\\\"highlight' 
    >>> print string
    class=\\"highlight
    

    and then remove it again

    >>> print re.sub('\\\\\\\\', r'\\', string)
    class=\"highlight
    
    0 讨论(0)
  • 2020-12-11 08:12

    why not use string.replace()?

    >>> s = 'some \\\\ doubles'
    >>> print s
    some \\ doubles
    >>> print s.replace('\\\\', '\\')
    some \ doubles
    

    Or with "raw" strings:

    >>> s = r'some \\ doubles'
    >>> print s
    some \\ doubles
    >>> print s.replace('\\\\', '\\')
    some \ doubles
    

    Since the escape character is complicated, you still need to escape it so it does not escape the '

    0 讨论(0)
提交回复
热议问题