main_string.replace(search_string, replace_string, count)
search_string: Required , string to search within main stringreplace_string: Required, string to replace if matching is found count: ( Optional ) Number of times the replacement to happen. By default all matches will be replaced. my_str='Welcome to PHP section of plus2net'
output=my_str.replace('PHP','Python')
print(output)
Ouptut
Welcome to Python section of plus2net
Replacing all occurrences of search string
my_str='Welcome to PHP section of plus2net. PHP has many buit-in functions'
output=my_str.replace('PHP','Python')
print(output)
Output
Welcome to Python section of plus2net. Python has many built-in functions
Using optional parameter count, we can replace only one occurrence.
my_str='Welcome to PHP section of plus2net. PHP has many built-in functions'
output=my_str.replace('PHP','Python',1)
print(output)
Output
Welcome to Python section of plus2net. PHP has many built-in functions
No matching is found, so input string is returned.
my_str='Welcome to PHP section of plus2net'
output=my_str.replace('MySQL','Python')
print(output) # Nothing replaced as no matching found
Output is here
Welcome to PHP section of plus2net
All String methods
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.