
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Regular Expression for String Replacement
In this article, we are going to discuss how to use regular expressions in place of a string.replace() method. As you may know, Python's built-in string.replace() method is used to replace given substrings in a string. But when we need more complex replacement features so Python's re (regular expressions) module is very helpful.
Regular expressions allow us to search for patterns and replace them with precise values, which makes string manipulation simpler.
Why Use Regular Expressions?
While string.replace() works well for simple tasks, it has its limitations, like it can only replace exact substrings and has limited ability to use pattern matching.
On the other hand, using regular expressions can match complex patterns, and it can also use special characters like \d, \w, etc., for more dynamic replacements.
Using re.sub() for String Replacement
Now we will see different examples to see how you can use regular expressions in place of the string.replace() method in Python.
Example: Basic Replacement
Here we will show you the basic usage of re.sub() function, where it will replace all occurrences of 'apple' with 'Mango'. See the following program -
import re # Using re.sub to replace text = "I like apple and apple shake." result = re.sub(r'apple', 'Mango', text) print(result)
Output
When you run the program, it will show this output -
I like Mango and Mango shake.
Example: Case-Insensitive Replacement
This example shows case insensitivity. By using flags=re.IGNORECASE, "Apple" and "apple" will be replaced with "Mango". This is useful when we do not want to think about the letter case when we are performing a search operation.
import re # Case-insensitive replacement text = "I like Apple and apple juice." result = re.sub(r'apple', 'Mango', text, flags=re.IGNORECASE) print(result)
Output
After running the program, you will get this result -
I like Mango and Mango juice.
Example: Replace Digits with a Word
In the example below, we will replace digits present in the given string with the word 'number'. It shows how to use regex to dynamically match and replace patterns that are not static strings.
import re # Replace all digits text = "I have 2 apples and 3 bananas." result = re.sub(r'\d+', 'number', text) print(result)
Output
This output will be displayed when the program runs -
I have number apples and number bananas.
Example: Dynamic Replacement
In this example, we will define a replace_with_square() function that accepts a match object and finds the matched integer, squares it, and returns the result as a string. The re.sub() method uses this function to replace each number in the original text with its square.
import re # Function to replace matched pattern def replace_with_square(match): number = int(match.group()) return str(number ** 2) text = "The numbers are 2, 3, and 4." result = re.sub(r'\d+', replace_with_square, text) print(result)
Output
You will see this result after executing the program -
The numbers are 4, 9, and 16.
Difference Between replace() and re.sub()
Here is a comparison table that shows the differences between the string.replace() and re.sub() methods -
Feature | replace() | re.sub() (regex) |
---|---|---|
Fixed text | Yes | Yes |
Pattern matching | No | Yes (powerful and flexible) |
Case insensitive | No (without extra code) | Yes (with flags=re.IGNORECASE) |
Replace by rules | No | Yes (use patterns and groups) |