如何在Python中替换字符串中的特定字符串?
我试图编写两个过程来替换python中字符串中匹配的字符串。 我要写两个程序 def匹配_箱(旧-新): 注意:输入是两个字符串,它返回一个替换转换器 def更换(x,另一个_字符串): 注:输入是前一过程中的转换器和字符串。它返回将转换器应用于输入字符串的结果 例如:如何在Python中替换字符串中的特定字符串?,python,loops,replace,Python,Loops,Replace,我试图编写两个过程来替换python中字符串中匹配的字符串。 我要写两个程序 def匹配_箱(旧-新): 注意:输入是两个字符串,它返回一个替换转换器 def更换(x,另一个_字符串): 注:输入是前一过程中的转换器和字符串。它返回将转换器应用于输入字符串的结果 例如: a = matched_case('mm','m') print replacement(a, 'mmmm') it should return m R = matched_case('hih','i') print re
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
另一个例子:
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
我不知道如何使用循环来完成整个过程。非常感谢所有能给你提示的人
def subrec(pattern, repl, string):
while pattern in string:
string = string.replace(pattern, repl)
return string
foo('mm','m','mmmm')
returnm
foo('hih','i','hhhhhhhhhh')
returnhi
foo('mm','m','mmmm')
returnm
foo('hih','i','hhhhhhhhhh')
returnhi
以下行中的某些内容可能会有所帮助:
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')
输出:
hi
m
matched_case(..)
返回一个替换转换器,因此最好使用(简单地说是匿名函数)来表示它。此匿名函数将字符串包装为已找到的字符串以及实际替换它的代码。以下行中的某些内容可能会有所帮助:
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')
输出:
hi
m
matched_case(..)
返回一个替换转换器,因此最好使用(简单地说是匿名函数)来表示它。这个匿名函数将字符串包装到找到的字符串和实际替换它的代码中。您的问题不太清楚…您可以清理一个位吗?您的问题不太清楚…您可以清理一个位吗?我建议对字符串变量使用与“str”不同的名称,因为这将隐藏“str”类,这可能会让人困惑。否则这个答案很好!为了模仿熟悉的re.sub
签名并指出替换是递归的:def subrec(pattern,repl,string):…
更多地考虑循环,可以将其简化为当src在a:a=a.replace(src,dst)(no if,no break)中时。@shihongzhi OP希望在两个函数中实现这一点。在我看来,最好像我下面所做的那样使用lambda
。我建议对字符串变量使用与“str”不同的名称,因为这将隐藏“str”类,这可能会让人困惑。否则这个答案很好!为了模仿熟悉的re.sub
签名并指出替换是递归的:def subrec(pattern,repl,string):…
更多地考虑循环,可以将其简化为当src在a:a=a.replace(src,dst)(no if,no break)中时。@shihongzhi OP希望在两个函数中实现这一点。在我看来,最好使用lambda
,就像我在下面所做的那样。