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.