tags:

views:

108

answers:

3

What is the best way to replace each occurrence of a leading or trailing hyphen with a space?

For example, I want

---ab---c-def--

to become

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

I'm trying to do this in Python, but I can't seem to come up with a regex that will do the substitution. I'm wondering if there is another, better way to do this?

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

Explanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (as many spaces as there were characters in said substring, in this case).

Alex Martelli
+3  A: 

Use a callable as the substitution target:

s = re.sub("^(-+)", lambda m: " " * (m.end() - m.start()), s)
s = re.sub("(-+)$", lambda m: " " * (m.end() - m.start()), s)
brool
Alex's answer is cleaner. :-)
brool
A: 

Whenever you want to match at the end of a string, always consider carefully 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'
>>>
John Machin