问题描述
我正在尝试编写两个过程来替换python中字符串中的匹配字符串.而且我必须编写两个过程.
I am trying to write two procedures to replace matched strings in a string in python.And I have to write two procedures.
defmatched_case(旧旧):.........
def matched_case(old new):.........
注意:输入是两个字符串,它将返回一个替换转换器.
note: inputs are two strings, it returns a replacement converter.
def替换(x,another_string):.....
def replacement(x,another_string):..........
注意:输入是上一过程的转换器和一个字符串.它返回将转换器应用于输入字符串的结果.
note:inputs are a converter from previous procedure, and a string. It returns the result of applying the converter to the input 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
我不确定如何使用循环来完成整个操作.非常感谢任何人都可以给出提示.
I am not sure how can I use loop to do the whole thing. Thanks so much for anyone can give a hint.
推荐答案
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
这篇关于如何在Python的字符串中替换某些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!