re.sub() in Python

In this tutorial, we will learn about the re.sub() function in Python and it’s application. To understand this function one must be familiar with the concept of Regular Expressions. Therefore, let’s revise Regular expressions first.

What are Regular Expressions?

A Regular Expression or (RegEX) is a stream of characters that forms a pattern.
Whether a string contains this pattern or not can be detected with the help of Regular Expressions.
It’s very easy to create and use Regular Expressions in Python- by importing re module.

import re

For more details on Regular Expressions, visit: Regular expression in Python

re.sub(): Syntax and Working

The re.sub() replace the substrings that match with the search pattern with a string of user’s choice.

  1. If the pattern is found in the given string then re.sub() returns a new string where the matched occurrences are replaced with user-defined strings.
  2. However, The re.sub() function returns the original string as it is when it can’t find any matches.

SYNTAX: re.sub(patternrepl, string[countflags])

      where,

  • pattern: Search pattern i.e. pattern by which you have to make replacements
  • repl: Replacement string os user’s choice
  • string: Original string
  • count: No of replacements to make (optional parameter)

Examples of re.sub() in Python

Example 1

In this example, our search pattern is blank space which is being replaced by full stops (‘.’).

import re
origional_str="I LOVE CODESPEEDY"
new_str=re.sub("\s",".",origional_str)
print(new_str)

OUTPUT:

I.LOVE.CODESPEEDY

Example 2

In this example, no matches are found therefore re.sub() returns the original string as it is.

import re
origional_str="I_LOVE_CODESPEEDY"
new_str=re.sub("\s",".",origional_str)
print(new_str)

OUTPUT:

I_LOVE_CODESPEEDY

Example 3

By providing the value count parameter we can control the no of replacements.

In this example, the value of count is 1. Therefore after one replacement the re.sub() will not make any further replacements.

import re
origional_str="I LOVE CODESPEEDY"
new_str=re.sub("\s",".",origional_str,1)
print(new_str)

OUTPUT:

I.LOVE CODESPEEDY

Also read,

groups() method in Regular Expression in Python

Leave a Reply

Your email address will not be published. Required fields are marked *