×

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

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Python Banner

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.