For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Python is known for its simple syntax and powerful string manipulation features. One such method is the replace() method, which allows you to replace parts of a string with new content. If you are looking to understand how to use this method efficiently, this guide on Replace in Python will walk you through the process with clarity and practical examples.
We will start by explaining what replace() does and how to use it correctly. You will then explore real-world examples - from basic substitutions to advanced use cases. Finally, we will cover when and why to use it, followed by detailed FAQs to answer any lingering questions.
Pursue our Software Engineering courses to get hands-on experience!
In Python, strings are immutable. This means you cannot change them directly after creation. However, Python provides built-in methods to create modified copies of a string. One such method is replace().
The replace() method helps you create a new string by replacing a specified part of the original string with a new value. It does not alter the original string. Instead, it returns a completely new one. This is useful when you need to update content in a string or clean data for processing.
You can also control how many replacements should be done. The optional count parameter allows you to limit the number of times the replacement occurs. Also, remember that the replace() method is case-sensitive. So, it treats "Hello" and "hello" as different values.
Take your skills to the next level with these top programs:
Let’s take a look at the syntax and understand it better with an example.
string.replace(old, new, count)
Here,
Example: Using All Three Parameters
Let’s write a Python program to understand how all three parameters work together.
# Original string with repeated words
text = "Learn Python, Practice Python, Enjoy Python"
# Replace only the first two occurrences of 'Python' with 'Coding'
updated_text = text.replace("Python", "Coding", 2)
# Print the modified string
print(updated_text)
Output:
Learn Coding, Practice Coding, Enjoy Python
Explanation:
Must Explore: String split() Method in Python
The replace() method in Python works in a variety of real-world scenarios. Let’s now walk through examples from beginner to advanced level. These examples show how flexible and powerful this method can be for handling string data.
Let’s begin with a simple case. Suppose you want to correct a spelling error in a sentence. You can use the replace() method to do this quickly and cleanly.
# Original sentence with a spelling error
sentence = "Pythonn is a beginner-friendly language."
# Replace the incorrect word with the correct one
fixed_sentence = sentence.replace("Pythonn", "Python")
# Print the corrected sentence
print(fixed_sentence)
Output:
Python is a beginner-friendly language.
Explanation:
This basic use is ideal for correcting errors in user input, form data, or file content.
Also read the Strip in Python article!
Now, let’s control how many times the replacement occurs. This is helpful when only specific changes are needed without altering every match in the string.
# A sentence with repeated punctuation
message = "Wait... What... Really..."
# Replace only the first two occurrences of "..." with "!"
updated_message = message.replace("...", "!", 2)
# Print the result
print(updated_message)
Output:
Wait! What! Really...
Explanation:
This technique is useful when cleaning logs or preparing formatted text where only specific occurrences matter.
In advanced use cases, you may need to apply replace() across dynamic content, such as lists or values coming from APIs. Here’s an example where we sanitize multiple strings inside a list.
# List of strings with inconsistent formatting
product_reviews = [
"This product is BAD.",
"BAD quality, would not recommend.",
"Service was not bad, actually good.",
"BAD packaging, but fast delivery."
]
# Use list comprehension to clean all reviews by replacing 'BAD' with 'Poor'
cleaned_reviews = [review.replace("BAD", "Poor") for review in product_reviews]
# Print the cleaned list
for review in cleaned_reviews:
print(review)
Output:
This product is Poor.
Poor quality, would not recommend.
Service was not bad, actually good.
Poor packaging, but fast delivery.
Explanation:
In such scenarios, Python's replace() allows fast and clean processing of multiple string entries.
Learn about Self in Python and Break Statement in Python to write better code!
The replace() method in Python is highly effective in everyday string processing. You should use it when you need clean, consistent, or corrected text data. Below are some practical scenarios where this method works best:
Also read the Top 43 Pattern Programs in Python to Master Loops and Recursion article!
The replace() method in Python is one of the most useful tools for handling string data. Whether you're correcting spelling errors, cleaning messy input, or customizing output, this method allows you to perform text replacements easily and accurately. Since strings in Python are immutable, each use of replace() returns a brand-new string, ensuring the original content remains unchanged.
No, the replace() method only works on string data types. If you want to use it with numeric data like integers or floats, you must first convert the number to a string using the str() function, then apply replace().
If the target substring isn’t found in the original string, the replace() method returns the string unchanged. No error is raised, and no partial changes are made. This feature makes it safe to use without additional checks.
No, it is not. The original string remains unchanged because strings in Python are immutable. The replace() method creates and returns a new string with the desired modifications, so the original can still be used as-is.
The replace() method performs simple, direct replacements based on exact matches. In contrast, regex-based substitutions (using re.sub()) allow complex pattern matching. Use replace() for straightforward changes and regex when patterns or wildcards are involved.
Yes, you can chain them. Doing so allows you to apply several replacements sequentially in a single line. However, order matters—each replace() call acts on the result of the previous one, so plan accordingly to avoid unexpected outcomes.
Absolutely. You can remove unwanted characters by replacing them with an empty string (""). For example, text.replace("-", "") will remove all dashes from the string. This method is commonly used for string cleaning or formatting.
The replace() method is efficient for short to medium strings. However, when used on very large texts or in loops over big datasets, performance can degrade. In such cases, optimizing logic or using compiled regex may yield better results.
The default replace() method is case-sensitive. To perform case-insensitive replacements, convert the entire string to lowercase or uppercase before applying replace(), or use re.sub() with the re.IGNORECASE flag from the re module for advanced control.
Yes, the replace in Python method can be used with variables that take user input. This makes it useful for dynamic applications like chatbots, form validation, or command-line tools, where you need to process user-submitted text on the fly.
While replace() works on substrings, translate() works at the character level and uses a translation table. If you need to replace many characters at once, especially single characters, translate() is often faster and more memory-efficient.
Understanding how to use Replace in Python builds a strong foundation in string manipulation. It teaches beginners how to work with immutable data and prepares them for more complex operations like data cleaning, formatting, and text preprocessing in real-world projects.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.