0

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.

1
  • Your question is not so clear...can you clean up a bit Commented Jun 1, 2012 at 6:23

2 Answers 2

3
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

Sign up to request clarification or add additional context in comments.

3 Comments

to mimic familiar re.sub signature and to point out that the substitution is recursive: def subrec(pattern, repl, string): ...
Thinking more about the loop, it can be simplified as while src in a: a = a.replace(src, dst) (no if, no break).
@shihongzhi OP wants that in two functions. IMO it is best to use a lambda like I have done below.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.