user8813607
user8813607

Reputation:

remove white spaces between special characters and words python

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

Upvotes: 0

Views: 1672

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

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.

Upvotes: 3

Related Questions