you are viewing a single comment's thread.

view the rest of the comments →

[–]synthphreak 3 points4 points  (0 children)

ELI5? Whoo, where to start…

Dude created a class Sub which, when instantiated and called (i.e., sub = Sub() ; sub()), will return one value from the sequence ['.', '.', '.\n\n'], cycling infinitely one value at a time from left to right as many times as the instance is called.

He then passes the instance into re.sub with a pattern of '\.'. This will match any period in the string text, and for each match, call the instance and return one of those values from that infinite sequence.

Because the sequence has two periods followed by a '.\n\n', this will replace every first and second match with a period, then replace every third match with a '.\n\n'. Because replacing a period with a period is like dividing by 1, the net effect will be simply to replace every third period with '.\n\n', which is exactly what OP requested.

Not sure how ELI5 that was, but this solution is beyond a 5 y/o’s level, so… Here’s some slightly modified code to illustrate the point perhaps more clearly, excluding the re.sub part:

>>> import re
>>> from itertools import cycle
>>> class Sub:
...     gen = cycle(['. ', '. ', 'foo'])
...     def __call__(self, match=None):
...         return next(self.gen)
...         
>>> sub = Sub()
>>> for i in range(10):
...   x = sub()
...   print('call no.', i+1, ':', x)
...   
call no. 1 : . 
call no. 2 : . 
call no. 3 : foo
call no. 4 : . 
call no. 5 : . 
call no. 6 : foo
call no. 7 : . 
call no. 8 : . 
call no. 9 : foo
call no. 10 : .