Online Tutorials & Training Materials | STechies.com
Register Login

How to Use String.Replace() in Python 3.x

|| 0

How to Use String.Replace() in Python 3.x
Stechies

In python replace() is an inbuilt function which returns a string by replacing sub-string with another sub-string, with all occurrences or specified numbers.

Syntax

original-string.replace(old-sub-string, new-sub-string[, max])

Parameters:

old-substring: (Required) : The old sub-string to replace
new-substring: (Required) : The new sub-string to replace with
max: (Optional) : Specify the number of occurrence of sub-string to replace, Default: All Occurrence

Return Value: String

Returns a new string which is copy of “original-string” with all or specified occurrence of old sub-string replaced with new sub-string 

Example:

# Python3 program to explain working of replace() method   
  
string = "Hello Stechies, Hello Python, Hello Programming, Hello Development" 
   
# Replace sub-string Hello with Hi  
print(string.replace("Hello", "Hi"))  
  
# Replace sub-string Hello with Hi only 3 occurrence   
print(string.replace("Hello", "Hi", 3))

# Check is replace() is case-sensitive
print(string.replace("hello", "Hi", 3))

Output: 

Hi Stechies, Hi Python, Hi Programming, Hi Development
Hi Stechies, Hi Python, Hi Programming, Hello Development
Hello Stechies, Hello Python, Hello Programming, Hello Development

Note: replace function is case-sensitive