On Aug 15, 6:28 pm, MRAB <pyt...@mrabarnett.plus.com> wrote: > > >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > > print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > 75,096,042,068,045 > > 509 > > 12,024 > > 7 > > 2,009 > > The call replaces a zero-width match with a comma, ie inserts a comma, > if certain conditions are met: > > "(?<=.)" > Look behind for 1 character. There must be at least one previous > character. This ensures that a comma is never inserted at the start of > the string. I could also have used "(?<!^)". Actually, it doesn't check > whether the first character is a "-". That's left as an exercise for the > reader. :-) > > "(?=(?:...)+$)" > Look ahead for a multiple of 3 characters, followed by the end of > the string.
Wow, well done. An exceptional recipe from Python's unofficial regex guru. And thanks for sharing the explanation. -- http://mail.python.org/mailman/listinfo/python-list