×

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the re- module first. It is generally used to replace the substrings in strings. The inbuilt module of python named regex supports the sub () method for searching and replacing specified patterns. This can also be used to split a string or pattern into one or more substrings or sub-patterns.

A module can be imported by the following statement

import re

Not a single element; multiple elements can be replaced using this function by using a list.

The general syntax for using this function is:

re.sub(old, new, string, [count=x,flags=])

Where the terms can be described as:

  • The first one, old, represents the string or pattern that needs to be replaced.
  • The second one, new, represents a string or pattern with which the old must be replaced.
  • The third term, string, denotes a string upon which the function or operation is to be executed (target string).
  • The fourth term, count, represents the count of replacements that must occur.
  • The fifth term, flags, is to shorten the code whose function is quite similar to that of a split operation.

After calling the function, it replaces a string by replacing the corresponding old one with a new pattern. If the one to be replaced(old) has not been found the string remains unchanged.

FunctionDetails
re.sub (old, new, string)All the occurrences of ‘old’ will be replaced by ‘new’.
re.sub (old, new, string, count=1)Only the first occurrence of ‘old’ be replaced by ‘new’ in the corresponding ‘string’.
re.sub (old, new, string, count=x)The first x occurrences of ‘old’ will be replaced by ‘new’.

Example 1: To replace all the white spaces in the string “India is one among the countries in the world which has powerful Intelligence agency" with "^".

import re 
str= “India is one among the countries in the world which has powerful Intelligence agency”
new_str=re.sub(r “\s”, “^”,str)
print(new)

Output:

What is the re.sub() function in Python

Here, we observe that all the occurrences of white spaces are replaced by "^", irrespective of the count of the number of white spaces.

Example 2: Replace the first occurrence of white space with "^" in the same above string.

import re
str= “India is one among the countries in the word which has powerful Intelligence agency”
new_str= re.sub(r “\s”, “^”,str, count=1)
print(new_str)

Output:

What is the re.sub() function in Python

You can observe that only the first occurrence of white space is replaced by “^,” and other occurrences remain the same.

Example 3: Replace the first three occurrences of white spaces with “^” in the same string mentioned above.

import re
str= “India is one among the countries in the word which has powerful Intelligence agency”
new_str=re.sub(r “\s”, “^”,str,count=3)
print(new_str)

Output

What is the re.sub() function in Python

Here, you can observe that only the first three occurrences of white space are replaced by the specified character.

Example 4: Replace the occurrences of “r” using the re.sub() function with “l” in the string “ragging”.

import re
string= “chugging”
new_str=re.sub(“r”, “l”, string)
print(new_str)

 Output:

What is the re.sub() function in Python

Since there are no occurrences of “r,” we observe that there is no change in the corresponding string (String remained unchanged).

A character set or number set can also be replaced by a single specified character.

Example: Replace all the lower-case letters in a string “Financial Year Is From 1 April to 31 March Of Its Successive Year” by “0”

import re
str= “Financial Year Is From 1 April to 31 March Of Its Successive Year”
new_str=re.sub(r “[a-z]”, “0”, str)
print(new_str)

Output:

What is the re.sub() function in Python

Here all the lower cases [a-z] got replaced by the specified character “0”.

We can also replace lower- and upper-case letters in a single shot or program using the parameter “flags.”

Example: Replacing all the lower case and upper-case letters in the above same string with “0” will be as follows

import re
str= “Financial Year Is From 1 April to 31 March Of Its Successive Year”
new=re.sub(r “[a-z]”, “0”,  str, flags=re.I)
print(new)

Output

What is the re.sub() function in Python

You can observe that all the characters, whether  the lowercase or upper case, are replaced by the specified character “0” in the corresponding string.


Related Topics

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.