python中的字符串后缀替换

时间:2011-06-15 19:39:50

标签: python string

我知道如何在python中进行字符串替换,但我只需要一种替换方法 如果序列位于单词的末尾。 例如:

rule: at -> ate
so:
cat -> cate
but:
attorney -> attorney

感谢。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

结果

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

PS

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

例如,由于使用了一个回调函数(此处名为 repl ,接收捕获的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)

结果

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

答案 2 :(得分:1)

您可以将正则表达式与re模块和以下代码一起使用:

re.sub(re.escape(suffix)+"$", replacement, word)

如果您需要为长于单个单词的文字执行此操作

re.sub(re.escape(suffix)+r"\b", replacement, word)

因为\b是一个单词边界,所以后缀为单词边界的后缀位于文本中任何单词的末尾

答案 3 :(得分:0)

后缀必须有一定的长度吗?如果没有,你可以从字符串的索引-1开始并向后工作你要搜索的字符数吗?然后就像通常那样执行字符串替换