Home > Enterprise >  how to remove substring with and without space
how to remove substring with and without space

Time:09-22

I have to remove first instances of the word "hard" from the given string but I am not sure how to do remove it both with and without spaces: For example: string1 = "it is a hard rock" needs to become "it is a rock" string2 = "play hard" needs to become "play"

However, when I use string1 = string1.replace(hard ' ', '', 1) it will not work on string2 as hard comes at the end without spaces. Any way to deal with this? Lastly if we have string3 string3 = "play hard to be hard" becomes "play to be hard" We want only the first occurrence to be replaced

CodePudding user response:

Maybe a simple

.replace(" hard", "").replace("hard ", "")

already works?
If not, I would suggest using a regular expression. But then you would have to give us a few more examples that need to be covered.

CodePudding user response:

Seems like a job for some regular expression:

import re

' '.join(filter(bool, re.split(r' *\bhard\b *', 'it is a hard rock', maxsplit=1)))

* eats up spaces around the word, \b guarantees only full words match, filter(bool, ...) removes empty strings between consecutive separators (if any) and finally ' '.join reinstates a single space.

  • Related