Python classic programming questions: string replacement

**Function prototype strreplace(str, oldString, newString) **
For example: >>> pstr = "Hello World!"; >>> afterReplaceStr = strreplace(pstr, "World"," Tom");
Then the value of afterReplaceStr is "Hello Tom!"

Method 1: Use string replacement

 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

Method 2: Use regular replacement

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

Method 3: Write your own replacement method

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

Python classic programming questions: string replacement
Python interview questions: string concatenation
Python string
Python string
Python answers questions
Python classic algorithm
Python string manipulation
Python network programming
Python interview questions
12. Network Programming in Python3
Python|Dynamic Programming Classic Case
Detailed Python IO programming
Str string in Python
Python classic interview question one​
Talking about Python functional programming
How Python converts string case
Python programming Pycharm fast learning
Python3 script programming commonly used.md
XTU programming Python training three
Python interview questions collection (three)
LeetCode brushing questions summary python3
Black Hat Programming Application Python2
Python string three formatted output