Extract Substring from a String in Python



In programming, a substring is a smaller part of the string. Extracting the substring is a task in Python, whether we are analysing the user input or manipulating URLs, we will find ourself to grab a portion of the string.

For achieving, Python provides the various way, Let's dive into the article to learn more about extracting the substring from the string.

Using Python slicing

The first approach is by using the Python slicing, It is the most common way to extract the substrings. Simply, we require the start and end indices.

Example

In the following example, we are going to extract the substring "TP" from the string "Welcome To TP".

str1 = "Welcome To TP"
result = str1[10:13]
print(result)

The output of the above program is as follows -

True

Using Python find() Method

The Python find() method is used to return the index of the created string where the substring is found. In this case, we are going to use the find() method on the input string to find the first occurrence of the substring. It returns -1 if not found.

Syntax

Following is the syntax for the Python find() method -

str.find(value, start, end)

Example

Following is the example where we are going to extract the substring "Vanakam" from the string "Hi, Hello, Vanakam" using the find() method with slicing.

str1 = "Hi, Hello, Vanakam"
x = str1.find("Vanakam")
result = str1[x:x + 7]
print(result)

The following is the output of the above program -

Vanakam

Using the Python "re" Module

The Python re module supports regular expressions, helping in string pattern matching and manipulation.

In this approach, we are going to use the re.search() method of Regular Expressions and extract the substring obtained from the input string using the regular expression.

Example

Consider the following example, where we are taking a string as input and we are extracting the numerical substring of the string using the regular expression '(\$[0-9\,]*)'.

import re
str1 = 'The phone is priced at $15,745.95 and has a camera.'
print("The numeric substring is:")
res = re.search(r'(\$[0-9\,]*.[0-9]{2})', str1)
if res:
   print(res.group(1))

The following is the output of the above program -

The numeric substring is:
$15,745.95
Updated on: 2025-05-20T11:44:44+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements