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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.