Python - String String Replace

Introduction

To replace a substring, you can use the string replace method:

Demo

S = 'testmy' 
S = S.replace('mm', 'xx')         # Replace all mm with xx in S 
print( S )

Result

The replace method takes as arguments the original substring and the string to replace it with:

Demo

print( 'aa$bb$cc$dd'.replace('$', 'TEST') )

Result

You can use replace with a third argument to limit it to a single substitution:

Demo

S = 'xxxxTESTxxxxTESTxxxx' 
print( S.replace('TEST', 'EGGS') )         # Replace all 
print( S.replace('TEST', 'EGGS', 1) )      # Replace one
# from w ww  .jav  a  2s  .  c  o  m

Result

Related Topics