如何替换字符串的后缀?
我知道怎么在Python中替换字符串,但我需要一种方法,只在单词的结尾进行替换。
比如说:
规则:at
替换成 ate
这样的话,cat
就变成了 cate
。
但是 attorney
就不会改变。
3 个回答
1
你可以使用正则表达式和re模块,配合下面的代码:
re.sub(re.escape(suffix)+"$", replacement, word)
如果你需要处理的文本长度超过一个单词
re.sub(re.escape(suffix)+r"\b", replacement, word)
因为\b
表示一个单词的边界,所以一个后缀后面跟着一个单词边界,就意味着它是在文本中某个单词的结尾。
7
其实没有什么特别的方法来做到这一点,不过其实也挺简单的:
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
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 regx.sub('ATU',ch)
结果:
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
使用正则表达式,我们可以完成非常复杂的任务。
比如,可以用特定的替换内容来替换多种不同的字符串,这得益于使用了一个回调函数(这里叫做 repl
,它会接收匹配到的对象)
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)
结果:
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