简体   繁体   中英

How can I replace certain string in a string in Python?

I am trying to write two procedures to replace matched strings in a string in python. And I have to write two procedures.

def matched_case(old new): .........

note: inputs are two strings, it returns a replacement converter.

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.

for example:

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

another example:

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') return m

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

Something on the lines of the below might help:

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(..) returns a replacement-converter, so it is best represented using a lambda (anonymous function to put it simply). This anonymous function wraps up the string to the found and the code that actually replaces it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM