avatarLaxfed Paulacy

Summary

The re.sub() method in Python's re module is used for substituting parts of a string that match a regular expression pattern with a specified

PYTHON — Python re.sub() Method Introduction

Programs must be written for people to read, and only incidentally for machines to execute. — Harold Abelson

PYTHON — Merging Grade Dataframes in Python

The re.sub() method in Python is part of the re module, which is used for working with regular expressions. This method is used to substitute a string with another string based on a specified regex pattern. It takes three positional arguments: pattern, repl, and string, as well as two optional arguments: count and flags.

The re.sub() method returns a string obtained by replacing occurrences of pattern in string with the replacement provided in repl. If the pattern is not found, the original string is returned unchanged. The optional count argument defines the maximum number of pattern occurrences to be replaced. If omitted or set to zero, all occurrences will be replaced. Additionally, the flags argument modifies the regex parsing behavior, enabling further refinement of pattern matching.

Let’s put the re.sub() method into action with some examples:

Example 1: Basic Usage

import re

text = "The quick brown fox jumps over the lazy dog"
result = re.sub(r"fox", "cat", text)
print(result)

Output:

The quick brown cat jumps over the lazy dog

In this example, the word “fox” is replaced with “cat” in the given text.

Example 2: Specifying Count

import re

text = "apple, apple, cherry, apple, banana"
result = re.sub(r"apple", "orange", text, count=2)
print(result)

Output:

orange, orange, cherry, apple, banana

Here, we replace the first two occurrences of “apple” with “orange”.

Example 3: Using Flags

import re

text = "The quick brown fox jumps over the lazy dog"
result = re.sub(r"\b\w{4}\b", "****", text, flags=re.IGNORECASE)
print(result)

Output:

The **** brown **** jumps over the **** ****

In this example, we replace all 4-letter words with “****”, while ignoring the case of the words.

These examples showcase how to use the re.sub() method to perform string substitutions based on regex patterns in Python.

PYTHON — Creating and Running Code Snippets in Jupyter using Python

Recommended from ReadMedium