Python Regex escape operator \ in substitutions & raw strings

First and foremost, replacement patterns ≠ regular expression patterns We use a regex pattern to search for matches, we use replacement patterns to replace matches found with regex. NOTE: The only special character in a substitution pattern is a backslash, \. Only the backslash must be doubled. Replacement pattern syntax in Python The re.sub docs … Read more

python replace single backslash with double backslash

No need to use str.replace or string.replace here, just convert that string to a raw string: >>> strs = r”C:\Users\Josh\Desktop\20130216″ ^ | notice the ‘r’ Below is the repr version of the above string, that’s why you’re seeing \\ here. But, in fact the actual string contains just ‘\’ not \\. >>> strs ‘C:\\Users\\Josh\\Desktop\\20130216’ >>> … Read more

using backslash in python (not to escape)

To answer your question directly, put r in front of the string. final= path + r’\xulrunner.exe ‘ + path + r’\application.ini’ But a better solution would be os.path.join: final = os.path.join(path, ‘xulrunner.exe’) + ‘ ‘ + \ os.path.join(path, ‘application.ini’) (the backslash there is escaping a newline, but you could put the whole thing on one … Read more

String.replaceAll single backslashes with double backslashes

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex: string.replaceAll(“\\\\”, “\\\\\\\\”); But you don’t necessarily need regex for this, simply because you want an exact character-by-character replacement and you don’t need patterns here. So String#replace() should suffice: … Read more