I would like to replace all occurrences of 3 or more "=" with an equal number "-".
def f(a, b):
'''
Example
=======
>>> from x import y
'''
return a == b
becomes
def f(a, b):
'''
Example
-------
>>> from x import y
'''
return a == b
My working but hacked solution is to pass the lambda to replfrom re.sub(), which captures the length of each match:
>>> import re
>>> s = """
... def f(a, b):
... '''
... Example
... =======
... >>> from x import y
... '''
... return a == b"""
>>> eq = r'(={3,})'
>>> print(re.sub(eq, lambda x: '-' * (x.end() - x.start()), s))
def f(a, b):
'''
Example
-------
>>> from x import y
'''
return a == b
Can I do this without having to pass a function to re.sub()?
My thinking would be what I need r'(=){3,}'(a variable-length capture group), but I think it re.sub(r'(=){3,}', '-', s)has a problem with greed.
Can I change the regex expression eqabove so that lambda is not needed?
source
share