Python regex to replace double backslash with single backslash -


i'm trying replace double backslashes single backslash. want replace 'class=\\"highlight' 'class=\"highlight'. thought python treats '\\' 1 backslash , r'\\+' string 2 backslashes (these 3 , 4 backslashes escaping). when try

in [5]: re.sub(r'\\+', '\\', string) sre_constants.error: bogus escape (end of line) 

so tried switching replace string raw string:

in [6]: re.sub(r'\\+', r'\\', string) out [6]: 'class=\\"highlight' 

which isn't need. tried 1 backslash in raw string:

in [7]: re.sub(r'\\+', r'\', string) syntaxerror: eol while scanning string literal     

why not use string.replace()?

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

or "raw" strings:

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

since escape character complicated, still need escape not escape '


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -