how to remove substring with and without space

Viewed 60

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.

3 Answers

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.

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.

Use str.partition—

# using if block
" ".join(s.strip() for s in thestring.partition("hard") if s != "hard")

# or with slice notation
" ".join(s.strip() for a in thestring.partition("hard")[::2])
Related