This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ezio.melotti
Recipients Samuel Warfield, ezio.melotti, mrabarnett
Date 2018-10-26.05:01:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1540530074.86.0.788709270274.issue35072@psf.upfronthosting.co.za>
In-reply-to
Content
I'm assuming you want to replace double backslashes with single backslashes in stringy_thing, so I defined stringy_thingy and tried both your snippets but they are both failing:
>>> stringy_thingy = r'foo\\bar\\baz'
>>> print(stringy_thingy)  # stringy_thingy contains double backslashes
foo\\bar\\baz
>>> re.sub(r'\\\\', chr(92), stringy_thingy)  # fails
Traceback (most recent call last):
  ...
  File "/usr/lib/python3.6/sre_parse.py", line 245, in __next
    self.string, len(self.string) - 1) from None
sre_constants.error: bad escape (end of pattern) at position 0
>>>
>>> parser = re.compile(r'\\\\')
>>> parser.sub(chr(92), stringy_thingy)  # also fails
Traceback (most recent call last):
  ...
  File "/usr/lib/python3.6/sre_parse.py", line 245, in __next
    self.string, len(self.string) - 1) from None
sre_constants.error: bad escape (end of pattern) at position 0

Replacing chr(92) with r'\\' works for both:
>>> print(re.sub(r'\\\\', r'\\', stringy_thingy))
foo\bar\baz
>>> print(parser.sub(r'\\', stringy_thingy))
foo\bar\baz

The docs[0] says: "repl can be a string or a function; if it is a string, any backslash escapes in it are processed."
So passing chr(92) (or '\\', which is equivalent) result in the above error ("bad escape (end of pattern)") because it's seen as an incomplete escape sequence.  Passing r'\\' seems to work as intended.

ISTM there is no bug and re.sub works as documented.  Can you provide a stringy_thingy for which the first of your snippet fails but the second succeeds?

[0]: https://docs.python.org/3/library/re.html#re.sub
History
Date User Action Args
2018-10-26 05:01:14ezio.melottisetrecipients: + ezio.melotti, mrabarnett, Samuel Warfield
2018-10-26 05:01:14ezio.melottisetmessageid: <1540530074.86.0.788709270274.issue35072@psf.upfronthosting.co.za>
2018-10-26 05:01:14ezio.melottilinkissue35072 messages
2018-10-26 05:01:14ezio.melotticreate