Python - replace multiple characters without .replace() -
the task transform string string without built-in .replace(). failed because forgot technically space string character. firstly transformed string list, see did unnecessarily. however, still doesn't work.
- i can replace "cat" "dog"
- i can replace "c" "dog"
i can't replace "a cat" "a dog".
i tried lambda or zip, don't know how it. have clue?
string = "alice has cat, cat has alice." old = "a cat" new = "a dog" def rplstr(string,old,new): """ docstring""" result = '' in string: if == old: = new result += return result print rplstr(string, old, new)
you can step through string, 1 character @ time, , test see if matches first character of old string. if matches, keep reference index, continue stepping through characters, trying match against 2nd char of old. keep going until match entire old string. if full match succeeds, use index of first character match , length of old string create new string new string inserted it.
def replstr(orig, old, new): = 0 output = '' temp = '' c in orig: if c == old[i]: += 1 temp += c else: = 0 if temp: output += temp temp = '' output += c if len(temp) == len(old): output += new temp = '' = 0 else: if temp: output += temp
Comments
Post a Comment