1

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 ", "")

1
  • What is your problem with the second trial? Commented Oct 13, 2015 at 4:34

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I didn't get to post an answer, so instead I'll just provide a link to a demo :)
@Green Cell, this doesn't work for a We are at a boat sale near a dock.
replace("a ", "") would work. (and yes I know this would fail if a was at the end) He asked for a specific string, so I gave him an answer for that specific string.
@GreenCell, what about a general solution?
Here's a general solution: 'a We are at a boat sale near a dock. a'.replace(' a ', ' ').lstrip('a ').rstrip(' a') Awaiting your answer too :)
3

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.'

2 Comments

That isn't the output OP asked for (extra spaces)
Now it's getting double spaces. Are you checking your answer?
1

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.

Comments

0

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(" "," ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.