Member-only story

Mastering Pattern Replacement with re.sub() in Python

Streamline Text Manipulation Tasks with Powerful Substitution Techniques

Max N
2 min readApr 6, 2024

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.

Using Backreferences

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet