4

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>

1
  • 1
    Note that if - or + are consecutive, re.sub('\s?([+-])\s?', r' \1 ', text) won't work well as there will be double spaces in the result. Commented Nov 22, 2018 at 9:58

2 Answers 2

5

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*
Sign up to request clarification or add additional context in comments.

3 Comments

why I'm not thinking about that :lol: will accepted in few minutes, thanks.
why \s* can match if there is no space?
Because * means repeat the previous token zero or more times (compared to ?, which means repeat the previous token zero or one time)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.