Reputation: 307
If I have a string "this is", and I want to replace "is" to "was". When I use replace ("is", "was")
, I got "thwas was", but what i am expecting is "this was",
is there any solution?
Upvotes: 2
Views: 8029
Reputation: 33029
You need to do something more sophisticated than a regular string replace. I'd suggest using Regular Expressions (the re
module), and using the \b
escape sequence to match word boundaries:
import re
re.sub(r"\bis\b", "was", "This is the best island!")
Result: 'This was the best island!'
By using the pattern r"\bis\b"
instead of just "is"
, you ensure that you only match "is" when it appears as a stand-alone word (i.e. there are no numbers, letters or underscore characters directly adjacent to it in the original string).
Here's some more examples of what matches and what doesn't:
re.sub(r"\bis\b", "was", "is? is_number? is, isn't 3is is, ,is, is. hyphen-is. &is")
Result: "was? is_number? was, isn't 3is was, ,was, was. hyphen-was. &was"
Upvotes: 7