Home > Mobile >  Adding a space after a special character
Adding a space after a special character

Time:01-03

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:

"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.

CodePudding user response:

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.

  • Related