简体   繁体   中英

regular expression remove words within string python

how do I remove the word a in this string?

We are at a boat sale near a dock.

result

We are at boat sale near dock.

I've tried:

removed = original.replace(" a", "") , removed = original.replace(" a ", "")

Looks like you just needed to replace with a space.

'We are at a boat sale near a dock.'.replace(" a ", " ")
# Result: We are at boat sale near dock. # 

I'm not sure what other strings you are trying to do this with but if you can get away with it try to use string ops like this instead of regex for better performance.

You can try by this way using regexp

 import re
 s= "We are at a boat sale near a dock."
 op = re.sub(r'\ba\b\s+',"",s)
 op 

In python console

>>> import re
>>> s = 'We are at a boat sale near a dock.'
>>> op = re.sub(r'\ba\b\s+',"",s)
>>> op
'We are at boat sale near dock.'

Two steps.

word_a = re.compile(r'\ba\b')
spaces = re.compile(r'\s+')
spaces.sub(' ', word_a.sub('', 'We are at a boat sale near a dock'))

\\b matches beginning or end of a word, but that alone will give us continuous spaces, so we replace multiple spaces \\s+ with one space.

you can try: 1. Using replace

>>> line = """ We are at a boat sale near a dock. """
>>> line.replace(" a "," ")
' We are at boat sale near dock. '
  1. Using regular expression and replace double space by single space:

    (re.sub(r'\\ba\\b','',line)).replace(" "," ")

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