Python - Replace Multiple Characters Without .replace()
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
Solution 1:
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 = 0while True:
next = string.find(old, index)
ifnext == -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.
Solution 2:
You can step through the string, one character at a time, and test to see if it matches with the first character of your old
string. If it matches, keep a reference to the index, then continue stepping through the characters, now trying to match against the 2nd char of old
. Keep going until you match the entire old
string. If the full match succeeds, use the index of the first character match and the length of the old
string to create a new string with the new
string inserted into it.
def replstr(orig, old, new):
i = 0output = ''
temp = ''for c in orig:
if c == old[i]:
i += 1
temp += c
else:
i = 0if temp:
output += temp
temp = ''output += c
iflen(temp) == len(old):
output += new
temp = ''
i = 0else:
if temp:
output += temp
Solution 3:
You can do it with slices:
def rplstr(string, old, new):
for i in xrange(len(string)):
if old == string[i:i+len(old)]:
string = string[:i] + new + string[i+len(old):]
returnstring
Solution 4:
You can do it in a simple and tiny way by using regular expressions.
import re
my_string = "Alice has a cat, a cat has Alice."
new_string = re.sub(r'a cat', 'a dog', my_string)
print new_string
Post a Comment for "Python - Replace Multiple Characters Without .replace()"