0

I'm trying to remove all white spaces between special characters and words.

For example,

"My Sister  '  s boyfriend is taking HIS brother to the movies  .  " 

to

"My Sister's boyfriend is taking HIS brother to the movies." 

How to do this in Python?

Thank you

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

3

Simple solutions like Simple way to remove multiple spaces in a string? don't work because they're just removing the duplicate spaces, so it would leave the spaces around dot and quote.

But can be done simply, with regex, using \W to determine non-alphanum (including spaces) and removing spaces before & after that (using \s* not \s+ so it can handle start & end of the string, not as satisfying because it performs a lot of replacements by the same thing, but simple & does the job):

import re

s = "My Sister ' s boyfriend is taking HIS brother    to the movies ."

print(re.sub("\s*(\W)\s*",r"\1",s))

result:

My Sister's boyfriend is taking HIS brother to the movies.
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thank you! but Im still having a white space between movies and . :(( –  Nov 11 '17 at 12:08
  • edited, to handle the dot in the end doesn't have space after it. Which wasn't the case in your question. Whatever, now that works even if it _ends_ with dot. – Jean-François Fabre Nov 11 '17 at 12:10