[英]How can I replace certain string in a string in Python?
我正在尝试编写两个过程来替换python中字符串中的匹配字符串。 而且我必须编写两个过程。
defmatched_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
我不确定如何使用循环来完成整个操作。 非常感谢任何人都可以给出提示。
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')
return hi
以下内容可能会有所帮助:
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(..)
返回一个替换转换器,因此最好使用lambda (将其简单化的匿名函数)表示。 该匿名函数将字符串包装到找到的字符串中,并实际替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.