VOOZH about

URL: https://www.geeksforgeeks.org/python/replace-in-python-to-replace-a-substring/

⇱ replace() in Python to replace a substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

replace() in Python to replace a substring

Last Updated : 31 Jan, 2025

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:


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.


Output
GeeksForGeeks

Converting a date format

We can use replace() to convert a date format from one style to another.


Output
21/01/2025
Comment
Article Tags:
Article Tags: