Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
regularexpressions

What is the re.sub() function in Python?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The re.sub() function belongs to the Regular Expressions (re) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string.

To use this function, we need to import the re module first.

import re

The re.sub() function stands for a substring and returns a string with replaced values. Multiple elements can be replaced using a list when we use this function.

Syntax

re.sub(pattern, repl, string, count=0, flags=0)

Parameters

  • The first parameter, pattern, denotes the string/pattern that needs to be replaced.

  • The second parameter, repl, denotes the string/pattern with which the pattern is replaced.

  • The third parameter, string, denotes the string on which the re.sub() operation will be executed.

  • The fourth parameter, count, denotes the number of replacements that should occur.

  • The fifth parameter, flags, helps to shorten the code and has similar functions as that of a split operation.

Code

Let’s look at the code snippet below to understand better.

# Importing re module
import re
# Given String
s = "I am a human being."
# Performing Sub() operation
res_1 = re.sub('a', 'x', s)
res_2 = re.sub('[a,I]','x',s)
# Print Results
print(res_1)
print(res_2)
# The original string remains unchanged
print(s)
Using sub() function in Python

Explanation

  • In line 2, we imported the re module.

  • In line 5, we entered a sample string.

  • In line 8, we used the re.sub() function to replace all the instances of a with x in the string s.

  • In line 9, we used the re.sub() function to replace all the instances of a and I with x in the string s.

  • In lines 12 and 13, we printed the results.

  • In line 16, the original string is printed

In this way, we can use the re.sub() function in Python.

RELATED TAGS

communitycreator
python
regularexpressions

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring