Python - String String Search

Introduction

To replace one fixed-size string that can occur at any offset, you can search for the substring with the string find method and then slice:

Demo

S = 'xxxxTESTxxxxTESTxxxx' 
where = S.find('TEST')            # Search for position 
print( where )                             # Occurs at offset 4 
S = S[:where] + 'EGGS' + S[(where+4):] 
print( S )# from ww w.  jav  a 2  s.  c om

Result

The find method returns the offset where the substring appears.

By default, searching from the front.

It returns -1 if the target string cannot be found.