2012-06-01 54 views
0

我想写两个过程来替换python中的字符串匹配的字符串。 我必须写两个程序。如何在Python中替换字符串中的某个字符串?

高清matched_case(新老): .........

注:输入两个字符串,它返回一个更换转换器。

DEF更换(X,another_string): ..........

注:输入是从前面的过程的转换器,和一个字符串。它将应用转换器的结果返回给输入字符串。

例如:

a = matched_case('mm','m') 
print replacement(a, 'mmmm') 
it should return m 

另一个例子:

R = matched_case('hih','i') 
print replacement(R, 'hhhhhhihhhhh') 
it should return hi 

我不知道我怎么可以用循环来做这件事。非常感谢任何人都可以给予提示。下面

+0

你的问题不是很清楚......你能清理一下 –

回答

3
def subrec(pattern, repl, string): 
    while pattern in string: 
     string = string.replace(pattern, repl) 
    return string 

foo('mm', 'm', 'mmmm')回报m

foo('hih', 'i', 'hhhhhhihhhhh')hi

+1

我建议使用与“str”不同的名称作为字符串变量,因为这会隐藏“str”类,这可能会让人困惑。否则,这个答案很好! – Blckknght

+0

是的,你是对的。我改变了它。 – shihongzhi

+0

来模拟熟悉的're.sub'签名并指出替换是递归的:'def subrec(pattern,repl,string):...' – jfs

0

上的东西线可能会有所帮助:

def matched_case(x,y): 
    return x, lambda param: param.replace(x,y) 

def replacement(matcher, s): 
    while matcher[0] in s: 
     s = matcher[1](s) 
    return s 

print replacement(matched_case('hih','i'), 'hhhhhhihhhhh') 
print replacement(matched_case('mm','m'), 'mmmm') 

OUTPUT:

hi 
m 

matched_case(..)返回替换转换器,所以最好使用lambda(匿名函数简单表示)来表示它。这个匿名函数将字符串包装到找到的和实际替换它的代码中。

+0

非常感谢,它的工作原理! –

相关问题