The task is to transform any string into any string without built-in .replace(). I failed because I forgot that technically space is also a string character. Firstly I transformed this string into the list, but now I see I did it unnecessarily. However, it still doesn't work.
I can't replace "a cat" into "a dog".
I tried with lambda or zip, but I don't really know how to do it. Do you have any clue?
string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"
def rplstr(string,old,new):
""" docstring"""
result = ''
for i in string:
if i == old:
i = new
result += i
return result
print rplstr(string, old, new)
This solution avoids string concatenation which can be less efficient. It creates a list of segments to join together at the end:
string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"
def rplstr(string, old, new):
""" docstring"""
output = []
index = 0
while True:
next = string.find(old, index)
if next == -1:
output.append(string[index:])
return ''.join(output)
else:
output.append(string[index:next])
output.append(new)
index = next + len(old)
print rplstr(string, old, new)
Giving:
Alice has a dog, a dog has Alice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With