1. Help Center
  2. Python Programming

How would you replace all occurrences of a substring with a new string?

The replace() function can be used with strings for replacing a substring with a given string. Syntax:
 
str.replace(old, new, count)

 

replace() returns a new string without modifying the original string.

 

Example -

 

>>"Hey John. How are you, John?".replace(“john", “John",1)

 

Output: “Hey John. How are you, John?