Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 9
    The repl argument to re.sub is a string, not a regex; applying re.escape to it doesn't make any sense in the first place. Commented Jan 29, 2018 at 6:54
  • 12
    @tripleee That's incorrect, the repl argument is not a simple string, it is parsed. For instance, re.sub(r'(.)', r'\1', 'X') will return X, not \1. Commented Apr 20, 2018 at 13:45
  • 10
    Here's the relevant question for escaping the repl argument: stackoverflow.com/q/49943270/247696 Commented Apr 20, 2018 at 13:54
  • 10
    Changed in version 3.3: The '_' character is no longer escaped. Changed in version 3.7: Only characters that can have special meaning in a regular expression are escaped. (Why did it take so long?) Commented Aug 11, 2018 at 21:58
  • @Flimm It's the \\1 that returns X, not the fact the second argument is a regex. You could do re.sub(r'(.)', '\\1', 'X') to get the exact same result. As far as I know, there is no reason to use a regex for the second argument. I could only assume it worked for you because it was using the string representation of the regex, and str(r"\1") == "\\1". Commented Jun 19, 2023 at 23:06