replace() in Python to replace a substring
Last Updated :
31 Jan, 2025
Improve
replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur.
For Example:
s = "hlo AB world"
# Replace "AB" with "C" in `s`
res = s.replace("AB", "C")
print(res)
Output
hlo C world
Syntax:
str.replace(pattern,replaceWith,maxCount)
Parameters:
- pattern: This specify string that we want to search for.
- replaceWith: This specify string we want to replace the old value with.
- maxCount: This specify how many times we want to replace something. If we don't set it then all occurrences will be replaced.
Removing extra spaces by using replace()
It means replacing multiple spaces between words with a single space or completely removing them to clean up the text.
s = "Geeks For Geeks"
# Replacing all spaces with an empty string
res = s.replace(" ", "")
print(res)
Output
GeeksForGeeks
Converting a date format
We can use replace() to convert a date format from one style to another.
# Backend date format
date = "2025-01-21"
# Converting the date format to DD/MM/YYYY
res = date.replace("-", "/").split("/")
res = f"{res[2]}/{res[1]}/{res[0]}"
print(res)
Output
21/01/2025