Reputation: 23360
I know how to make string replacements in Python but I need a way to replace only if the sequence is located at the end of the word.
For example:
Rule: at
→ ate
So cat
is changed to cate
.
But attorney
stays unchanged.
Upvotes: 2
Views: 7764
Reputation: 27575
A regex can do that with ease:
import re
regx = re.compile('at\\b')
ch = 'the fat cat was impressed by all the rats gathering at one corner of the great room'
print ch
print regx.sub('ATU',ch)
Result:
the fat cat was impressed by all the rats gathering at one corner of the great room
the fATU cATU was impressed by all the rats gathering ATU one corner of the greATU room
With regexes, we can perform very complicated tasks.
For example, replacing several kinds of strings with a particular replacement for each, thanks to the use of a callback function (here named repl
, that receives catched MatchObjects)
import re
regx = re.compile('(at\\b)|([^ ]r(?! ))')
def repl(mat, dic = {1:'ATU',2:'XIXI'}):
return dic[mat.lastindex]
ch = 'the fat cat was impressed by all the rats gathering at one corner of the great room'
print ch
print regx.sub(repl,ch)
Result:
the fat cat was impressed by all the rats gathering at one corner of the great room
the fATU cATU was imXIXIessed by all the rats gathXIXIing ATU one cXIXIner of the XIXIeATU room
Upvotes: 5
Reputation: 20277
You could use regular expressions with the re module and the following code:
re.sub(re.escape(suffix)+"$", replacement, word)
If you need to do this for text longer than a single word
re.sub(re.escape(suffix)+r"\b", replacement, word)
because \b
is a word boundary, so a suffix followed by a word boundary is at the end of any word in the text
Upvotes: 1
Reputation: 107608
There is no special method to do this, but it's quite simple anyways:
w = 'at'
repl = 'ate'
s = 'cat'
if s.endswith(w):
# if s ends with w, take only the part before w and add the replacement
s = s[:-len(w)] + repl
Upvotes: 7