**Function prototype strreplace(str, oldString, newString) **
For example: >>> pstr = "Hello World!"; >>> afterReplaceStr = strreplace(pstr, "World"," Tom");
Then the value of afterReplaceStr is "Hello Tom!"
def strreplace_v1(old_str, key, value):
# Replace one or several strings of a string
new_str = old_str.replace(key, value)return new_str
import re
def strreplace_v2(msg, key, value):'''Replace one or several strings of a string'''
m = re.compile(key)
ret = m.sub(value, msg)return ret
def strreplace_v3(msg, key, value):'''Replace one or several strings of a string'''
n =len(key)
# Use python's str.index()
# i = msg.index(key)
# Use handwritten functions
i =str_index(msg, key)
j = i + n
ret = msg[:i]+ value + msg[j:]return ret
def str_index(msg, key):'''Find the position of the string key in the string msg
Handwriting str.index()function
'''
i = j =0
n =len(msg)
m =len(key)
flag = False
while i < n and not flag:
# Check the 0th letter
if msg[i]!= key[0]:
i +=1else:
# Same, detect subsequent letters
for k inrange(1, m):if msg[i + k]!= key[j + k]:
i += k +1breakelse:
# turn up
return i
raise ValueError('substring not found')
pstr ="Hello World!"
afterReplaceStr =strreplace_v3(pstr," World"," Tom")print(afterReplaceStr)
Recommended Posts