Replacing leading and trailing hyphens with spaces?

What's the best way to replace every occurrence of a leading or trailing hyphen with a space?

For example, I want

--- anyhow --- with clarity -

to become

000ab --- c-def00 (where zeros are spaces)

I'm trying to do this in Python, but I can't think of a regex that will do the substitution. I am wondering if there is another way to do this?

+2


source to share


3 answers


re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--')

      



Explanation: pattern matches 1 or more leading or trailing dashes; the substitution is best done by a callee that takes each matching object - so m.group () is a substring of the fit - and returns the string that should replace it (as many spaces as there are characters in the specified substring, in this case).

+5


source


Use a callable as a substitution target:



s = re.sub("^(-+)", lambda m: " " * (m.end() - m.start()), s)
s = re.sub("(-+)$", lambda m: " " * (m.end() - m.start()), s)

      

+3


source


Whenever you want to align at the end of a line, always carefully consider whether you need $

or \Z

. Examples using '0' instead of '' for clarity:

>>> re.sub(r"^-+|-+\Z", lambda m: '0'*len(m.group()), "--ab--c-def--")
'00ab--c-def00'
>>> re.sub(r"^-+|-+\Z", lambda m: '0'*len(m.group()), "--ab--c-def--\n")
'00ab--c-def--\n'
>>> re.sub(r"^-+|-+$",  lambda m: '0'*len(m.group()), "--ab--c-def--\n")
'00ab--c-def00\n'
>>>

      

0


source







All Articles