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>
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 \ss with * instead of ?, so that, for example, 3   + 5 gets prettified to 3 + 5:
\s*([+-])\s*
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With