VOOZH about

URL: https://www.geeksforgeeks.org/python/python-string-replace/

⇱ Python String replace() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python String replace() Method

Last Updated : 17 Nov, 2025

The replace() method returns a new string where all occurrences of a specified substring are replaced with another substring. It does not modify the original string because Python strings are immutable.

Example : This example replaces every occurrence of a substring in the given string, creating a fully updated new string.


Output
Coding is fun. Coding is powerful.

Syntax

string.replace(old, new, count)

Parameters:

  • old: Substring to be replaced.
  • new: Substring to insert in place of old.
  • count (optional): Maximum number of replacements. If not provided, all occurrences are replaced.

Return Value: Returns a new string with the specified replacements. The original string remains unchanged.

Examples

Example 2: Here, only the first occurrence of a substring is replaced using the count parameter.


Output
orange apple apple

Explanation: s.replace("apple", "orange", 1) replaces "apple" only once due to count=1.

Example 3: This example demonstrates that replace() treats uppercase and lowercase characters as different, replacing only exact matches.


Output
Hi World! hello world!
Hello World! hi world!

Explanation:

  • s.replace("Hello", "Hi") affects only the capitalized "Hello".
  • s.replace("hello", "hi") affects only the lowercase "hello".
Comment
Article Tags: