Python

Python String replace Method

Hello in this tutorial, we will understand the string replace() method in python programming.

1. Introduction

replace() method in python programming returns a copy of a string where all occurrences of a substring are replaced by the new string. The method also accepts an optional count argument only if the first count occurrences are to be replaced.

1
my_string.replace(old_string, new_string, count)

where,

  • old_string – Represents the substring you want to replace
  • new_string – Represents the new substring which would replace the old_string
  • count – Number of times to process the replace

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python String replace Method

I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of their choice.

2.1 String Replace Example

Let us understand this with the help of a code snippet.

String replace in Python

01
02
03
04
05
06
07
08
09
10
# replace() method
string = 'one one is a fastest animal, two two was one too.'
print('Original string = {}'.format(string))
print('\n')
# prints the string by replacing one by three
print(string.replace('one', 'three'))
print('\n')
# prints the string by replacing only 3 occurrences of one
count = 2
print(string.replace('one', 'three', count))

If everything goes well the following output will be shown in the IDE console.

Console Output

1
2
3
Original string = one one is a fastest animal, two two was one too.
three three is a fastest animal, two two was three too.
three three is a fastest animal, two two was one too.

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • An introduction to replace() method in the python programming language
  • Sample program to understand the replace() in the python programming language

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was an example of replace() method in python programming.

Download
You can download the full source code of this example here: Python String replace Method

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button