Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a space after a special character

Im trying to add a space after a special character if there isn’t one already in a string.

This is my code

import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
for i in re.finditer(r"\?|!|\.", line):
if line[i.end()]!=' ':
    line=line.replace(line[i.end()],line[i.end()]+' ')

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Hello there! This is Robert. Happy New Year! Are you surprised? Im not."

Output from my code:

"Hello t here!  This is Robert . Happy New Year!A re you surprised? Im not ."

I still haven’t figured out why it doesn’t work.

>Solution :

Use

re.sub(r'([!?.])(?=\S)', r'\1 ', line)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [!?.]                    any character of: '!', '?', '.'
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \S                       non-whitespace (all but \n, \r, \t, \f,
                             and " ")
--------------------------------------------------------------------------------
  )                        end of look-ahead

Python code:

import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
line = re.sub(r'([!?.])(?=\S)', r'\1 ', line)

Results: Hello there! This is Robert. Happy New Year! Are you surprised? Im not.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading