Reputation: 19154
I'm trying to add one space before and after +-
, using re.sub
(only) what expression to use?
import re
text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e"""
text = re.sub('(\s?[+-]\s?)', r' \1 ', text)
print(text)
expected result:
a + b
a + b - c
a + b - c
a + b - c + d - e
a + b - c + d - e
<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>
<div data-datacamp-exercise data-lang="python">
<code data-type="sample-code">
import re
text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e
"""
text = re.sub('(\s?[+-]\s?)', r' \1 ', text)
print(text)
</code>
</div>
Upvotes: 4
Views: 137
Reputation: 370679
Try capturing only the [+-]
, and then replace with that group surrounded by spaces:
text = re.sub('\s?([+-])\s?', r' \1 ', text)
<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>
<div data-datacamp-exercise data-lang="python">
<code data-type="sample-code">
import re
text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e
"""
text = re.sub('\s?([+-])\s?', r' \1 ', text)
print(text)
</code>
</div>
You also might consider repeating the \s
s with *
instead of ?
, so that, for example, 3 + 5
gets prettified to 3 + 5
:
\s*([+-])\s*
Upvotes: 5
Reputation: 71451
You can use a lambda
function with re.sub
:
import re
new_text = re.sub('(?<=\S)[\+\-](?=\S)', lambda x:f' {x.group()} ', text)
Output:
a + b
a + b - c
a + b - c
a + b - c + d - e
a + b - c + d - e
Upvotes: 2