Member-only story
In Python, regular expressions are a staple for text processing tasks. Among the numerous functionalities they offer, the re.sub()
method stands out as a powerful tool for replacing matched patterns within strings.
In this article, we'll explore how to effectively utilize re.sub()
to streamline your text manipulation tasks with practical examples.
Introduction to re.sub()
The re.sub()
method in Python's regular expression module (re
) is used to replace occurrences of a pattern within a string with a specified replacement. It provides a flexible and efficient way to perform pattern-based substitutions.
Basic Usage
Let’s start with a simple example demonstrating the basic usage of re.sub()
.
import re
text = 'Hello, world!'
pattern = 'world'
replacement = 'Python'
new_text = re.sub(pattern, replacement, text)
print(new_text) # Output: Hello, Python!
In this example, the pattern ‘world’ is replaced with ‘Python’ in the original text.