python中的字符串后缀替换

tom*_*mes 2 python string

我知道如何在python中进行字符串替换,但只有当序列位于单词的末尾时才需要替换方法.例如:

rule: at -> ate
so:
cat -> cate
but:
attorney -> attorney
Run Code Online (Sandbox Code Playgroud)

谢谢.

Joc*_*zel 6

没有特殊的方法可以做到这一点,但它仍然很简单:

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
Run Code Online (Sandbox Code Playgroud)


eyq*_*uem 5

正则表达式可以轻松地做到这一点:

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
print regx.sub('ATU',ch)
Run Code Online (Sandbox Code Playgroud)

结果

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
Run Code Online (Sandbox Code Playgroud)

.

PS

使用正则表达式,我们可以执行非常复杂的任务.

例如,由于使用了一个回调函数(此处名为repl,接收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
print regx.sub(repl,ch)
Run Code Online (Sandbox Code Playgroud)

结果

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
Run Code Online (Sandbox Code Playgroud)