简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM