How to Search and Replace with Python

Python is a dynamic object-oriented programming language that can be used for many kinds of software development. Python’s String class has a search-and-replace method named “replace.” It’s very useful but doesn’t support regular expressions. So here is the instruction to tell you how to search and replace with Python.


1. Run Python.

2. Type the following into the interpreter:

s = “This is a string.”

3. Perform a search and replace with the “replace” method:

s = s.replace(“This”, “That”)

The result will be “That is a string.”

4. Because once the strings are defined, they cannot be changed. So it would be important to reassign the new string created by the “replace” command to the same variable name. Type the following to search:

s = s.replace(“find”, “replace”, count)

For example:

s = “This is a string. This is another string.”

s = s.replace(“This”, “That”, 1)

Since the count value is set to “1,” only the first instance will be replaced, giving the following result: “That is a string. This is another string.”