
Hello Techies,
In this article, we will learn about Python Find and Replace methods in detail with various examples. We will use the built-in function as well as some custom code.
These are the most useful methods when working with strings in Python, you may need to find strings for some patterns or replace some parts of the string with another substring.
Python has useful string methods to find() and replace() that help us perform these string processes.
Table of Contents
Python find() method
- The find() method detects the first occurrence of a specified value.
- If the value is not found then the find() method returns -1.
Syntax of Python find() method
string.find(value, start, end)
Parameters for the find() method
Here are the three parameters of the string find() method in Python:
- value: The value you want to find in the given string.
- start: (Optional) Start value from which the value search begins. By default, it is 0.
- end: (Optional) The final value where the search for a substring ends. By default, the value is the length of the string.
Example of Python find() method
Example 1: Using find() method for value exist
txt = "I Love Python" x = txt.find("Python") print(x)
Output:
7
Example 2: Using find() method for value is not present
txt = "I Love Python" x = txt.find("Developer") print(x)
Output:
-1
Example 3: Using the find() method by defining start arguments.
txt = "I Love Python" x = txt.find("o", 2) print(x)
Output:
3
Example 4: Using the find() method by defining start and end arguments.
txt = "I Love Python" x = txt.find("o", 2, 12) print(x)
Output:
3
Python replace() method
Sometimes in Project, you may want to replace the occurrences of the substring with a new string, and Python has a built-in method replace() to achieve this.
The replace() method replaces each matching occurrence of the old character in the string with a new character.
Syntax of replace() method
string.replace(old_value, new_value, count)
Parameters for the replace() method
Here are the three parameters of the replace() method in Python:
- old_value: String to find.
- new_value: String to replace the old value.
- count: (Optional)A number that specifies how many old value occurrences you want to change. The default is all occurrences.
Example of replace() method
Example 1:
txt = "I Love Python" x = txt.replace("Love", "Like") print(x)
Output:
I Like Python
Example 2: Replace() method using count argument
txt = "one one two three four one five" x = txt.replace("one", "three", 2) print(x)
Output:
three three two three four one five
I hope you have understood the concept of the Python find() & replace() method. If you have any questions please comment below.
