How would I use the python "re" module to replace a word, i.e., 'co' with an empty string, i.e., '' in a given text, only if:
- the word is at the end of the text and there's a space before the word
- the word is not the final word in the text but there's a space at beginning, and then another space at the end of the word
I.e.,
# word is not the final word in the text but there's a space at beginning, and then another space at the end of the word
txt = 'A co is mine'
txt_after_replace = 'A is mine'
txt = 'A column is mine'
txt_ater_replace = 'A column is mine'
# word is the end of the text and there's a space before the word
txt = 'my co'
txt_after_replace = 'my'
txt = 'my column'
txt_after_replace = 'my column'
If I do: txt.replace(' co', '') these two cases will fail: txt = 'my column', txt_ater_replace = 'A column is mine'. Since it won't check for the end of text right after the word or for a space in the text right after the word.
I think the re.sub module would come to the rescue here but I'm unsure how.
This should work for any general word, i.e., 'co' in this case.
\b\w+$(which would slightly over-match if there's punctuation before the word) and the second one could use capture groups" (\w+) .*$"