Substitute Substring In Python

Posted August 12, 2022 by Rohith ‐ 1 min read

Substitute in python can be achieved in many ways. In this article we will using python string method or using regular expressions

Substitute Substring Using Replace Method

replace is a python string method. Syntax for the replace method is shown below

Syntax:

replace(self: str, old: str, new: str, count: int=-1) -> str

Here, self is the string object. old is the string to be replaced. new is the substring to be replaced with. count is an optional parameter to replace the number of instances.

Example:

string = 'Protect the Gotham City'
new_string = string.replace('Protect', 'Destroy')

Output:

print(new_string)
# Destroy the Gotham City

Substitute Substring Using regex

re.sub() method can be used to replace the substring in python.

Syntax:

sub(pattern: str, repl: str, string: str, count: int, flags: str) -> str

count and flags are optional parameters.

It can be explained better with example:

Example:

import re
re.sub('^//', '', string, flags=re.MULTILINE)

or

Example:

import re
re.sub(re.compile('^//', re.MULTILINE), '', string)

More Complex Example

For example, we have s3 path data/month=may/dataFile.snappy.parquet. We want to replace the string with data/month=05/dataFile.snappy.parquet

import re

path = 'data/month=may/dataFile.snappy.parquet'
new_path = re.sub('month=\w+', 'month=05', path)

Output:

print(new_path)
# 'data/month=05/dataFile.snappy.parquet'

Subscribe For More Content