Python substring

In Python, we don’t have an exclusive string function to find or return a substring. However, we have multiple options to extract or return a substring in the Python programming language. In this section, we explain to you all the possible options to return a substring in Python with examples. To get or find the string substring in Python, we use some built-in string functions and functionalities. 

Python substring Example

The following are the list of examples for extracting or returning substring in Python

Python String slicing to get substring

In Python, you can slice any object to return a portion of the Object or substring. In this example, we use the slicing concept to return a Python substring. Slicing accepts three arguments, and they are the start and endpoint and steps.

# Python substring Example
 
string = 'Tutorial Gateway'
 
print(string[:]) # returns complete string
 
print(string[: 5]) # substring From 0 to 5
 
print(string[1 : 10])
 
print(string[2 : 13])
 
print(string[5 : 15]) # substring from 5 to 15

Python String slicing to return a substring output

Tutorial Gateway
Tutor
utorial G
torial Gate
ial Gatewa

The Python string slicing accepts the negative values as well to get the substring. In this example, we are using Negative values as the endpoint. Negative values mean, it counts from rightmost character to the left. It means, print(string[2 : -13]) returns substring from 2 to end -13 (removes rightmost 13 characters).

string = 'Learn Python Tutorial'
 
print(string[:])
 
print(string[: -5]) # substring from 0 to 
 
print(string[1 : -10])
 
print(string[2 : -13])
 
print(string[4 : -1])
 
print(string[3 : -4])

Python String substring using negative slice values output

Learn Python Tutorial
Learn Python Tut
earn Pytho
arn Py
n Python Tutoria
rn Python Tuto

In this example, we are using the third value inside the slicing. It can help you to skip the characters within a string and returns the substring. For example, print(string[0: 14: 2]) returns a substring from 0 to 14, where it skips alternative characters (every 2nd character). I suggest you refer to the Python String and Python String Functions in Python.

string = 'Python Programming Language for Free'
 
print(string[:])
 
print(string[0 : 14]) # is equal to print(string[0 : 14 : 1])
 
print(string[0 : 14 : 2]) 
 
print(string[0 : 14 : 3]) # skips every third character
 
print(string[2 : 30 : 2])
 
print(string[1 : 25 : 3])
Python substring 3

Python substring functions

Instead of slicing the object every time, you can create a function that slices the string and returns a substring. By this, you can allow users to use this function as any built-in function.

In this example, we defined a function that accepts the string, starting point, and endpoint. Next, it slices the string (first argument) from start to endpoint and returns the result. Please refer to Python Functions and Types of Functions to understand the function creation and types

def substring(string, start, end):
    return string[start:end]
 
string = 'Python Programming'
 
print(substring(string, 1, 5))
 
print(substring(string, 2, 10))
 
print(substring(string, 0, 18))
 
print(substring(string, 3, 14))
 
print(substring(string, 2, 15))

String substring functions output

ytho
thon Pro
Python Programming
hon Program
thon Programm

In the example, we are using the start point and length. This function accepts a string and optional arguments start point and length.

def substring(string, start = None, length = None):
    return string[start : ][: length]
 
string = 'Learn Python Programming Language'
 
print(substring(string))
 
print(substring(string, 3))
 
print(substring(string, 2, 19))
 
print(substring(string, length = 10))

String substring output

Learn Python Programming Language
rn Python Programming Language
arn Python Programm
Learn Pyth

It is a better approach than the above substring example.

def substring(string, start = None, length = None):
    return string[start : length]
 
string = 'Learn Python Programming Language'
 
print(substring(string))
 
print(substring(string, 7))
 
print(substring(string, 2, 19))
 
print(substring(string, 3, 22))
 
print(substring(string, length = 15))

String substring output

Learn Python Programming Language
ython Programming Language
arn Python Progra
rn Python Programmi
Learn Python Pr

In this example, we use another argument called steps to skips the characters within a string.

def substring(string, start, end, steps = 1):
    return string[start : end : steps]
 
string = 'Python Programming Language for Free'
 
print(substring(string, 1, 5))
print(substring(string, 1, 5, 1))
print(substring(string, 1, 5, 2))
 
print(substring(string, 2, 30))
print(substring(string, 2, 30, 2))
print(substring(string, 2, 30, 3))
 
print(substring(string, 0, 35, 1))
print(substring(string, 0, 35, 2))
print(substring(string, 0, 35, 3))
print(substring(string, 0, 35, 4))

String substring output

ytho
ytho
yh
thon Programming Language fo
to rgamn agaef
tnrrmgaueo
Python Programming Language for Fre
Pto rgamn agaefrFe
Ph oai na rr
PoranaafF

Python substring in reverse

By using the Negative values, you can also return a substring in reverse order.

string = 'Learn Python Programming Language'
 
print(string[:: -1])
 
print(string[19:: -1])
 
print(string[4 :: -1])
 
print(string[9 :: -1])
 
print(string[11 :: -1])

String substring in reverse using negative slicing output

egaugnaL gnimmargorP nohtyP nraeL
margorP nohtyP nraeL
nraeL
htyP nraeL
nohtyP nraeL

substring using For Loop

You can also use for loop with range function to return a substring.  For this, we have to use print function along with end argument. This Python string example returns a substring starts at 3 and ends at 24.

string = 'Python Programming Language for Free'
 
for n in range(3, 25):
    print(string[n], end = '')

String substring using For Loop output

hon Programming Langua

substring slice

The Python slice function allows you to slice the given string or returns a substring. This function accepts start and endpoint. By using these values, you can return the substring from any given start point to the endpoint. For example, slice(3, 13) returns a substring from the character at 4 to 13.

string = 'Learn Python Language for Free'
 
sub1 = slice(4)
print(string[sub1])
 
sub2 = slice(3, 13)
print(string[sub2])
 
sub3 = slice(1, 21)
print(string[sub3])
 
sub4 = slice(1, 28)
print(string[sub4])
 
sub5 = slice(7, 29)
print(string[sub5])

String substring using slicing

Lear
rn Python 
earn Python Language
earn Python Language for Fr
ython Language for Fre

Here, we use negative values to slice from right to left. Next, we used the -1 as the third argument to return the substring in reverse order.

string = 'Learn Python Language for Free'
 
sub1 = slice(-1, -7, -1)
print(string[sub1])
 
sub2 = slice(-7, 3, -1)
print(string[sub2])

String substring using negative values slicing

eerF r
of egaugnaL nohtyP n

Python substring match

Check whether the substring is present in the given string or not using the Python If Else and not In operator.

string = 'Hello World'
 
substring = 'Hello'
 
if substring not in string:
    print('We haven\'t found what you are looking for = ', substring)
else:
    print('We found the Matching substring = ', substring)

Finding the substring in a string output

We found the Matching substring = Hello

This time, we are checking the non-existing substring

string = 'We are abc working at abc company'
 
substring = 'xyz'
 
if substring in string:
    print('We found the Matching substring = ', substring)
else:
    print('We haven\'t found what you are looking for = ', substring)

Searching for non-existing substring output

We haven't found what you are looking for =  xyz

Not in operator is not the only way to check the substring match. You can use the Python find function.

string = 'We are abc working at abc company'
 
substring = 'abc'
 
if string.find(substring) == -1:
    print('We haven\'t found what you are looking for = ', substring)
else:
    print('We found the Matching substring = ', substring)

String substring using not in operator output

We found the Matching substring = abc

Python substring before Character

In this example, we show how to return a substring before the character. For this, we are using the built-in string function called Python Split Function. Here, we used the Python split string function to split the given string into two strings using the space, and we assigned those splitter strings to two variables. 

# Python substring before Character Example
 
string = 'Tutorial Gateway'
 
first, second = string.split(' ')
 
print('Substring Before Character space = ', first)

String substring before a character output

Substring Before Character space = Tutorial

In this example, we use this split function to return the substring before : character and after : character. 

time = '22:30:55'
 
hour, minute, second = time.split(':')
 
print('Subtring Before First Character : = ', hour)
print('Subtring Before Second Character : = ', minute)
print('Subtring After Second Character : = ', second)
 
print('------------')
first, second = time.split(':', 1)
print('Subtring Before First Character : = ', first)
print('Subtring After First Character : = ', second)
 
print('------------')
first, second = time.rsplit(':', 1)
print('Subtring Before Second Character : = ', first)
print('Subtring After Second Character : = ', second)

String substring date and time output

Subtring Before First Character : =  22
Subtring Before Second Character : =  30
Subtring After Second Character : =  55
------------
Subtring Before First Character : =  22
Subtring After First Character : =  30:55
------------
Subtring Before Second Character : =  22:30
Subtring After Second Character : =  55

Python substring after Character

In this example, we show how to return a substring after character. 

# Python substring after Character Example
 
string = 'Hello World!'
 
first, second = string.split(' ')
 
print('String Before the Space = ', first)
print('String After the Space = ', second)

String substring after Character output

String Before the Space =  Hello
String After the Space =  World!

Sometimes, you might ask to return the substring before @ symbol and domain name as a separate string. In this scenario, you can use the split function to split the string into two substrings.

string = '[email protected]'
 
name, domain = string.split('@')
 
print('Subtring Before Character @ = ', name)
print('Subtring After Character @ = ', domain)

String substring using split function output

Subtring Before Character @ =  contact
Subtring After Character @ =  tutorialgateway.org

Python substring Index

The index function used to find the index position of the given substring or character. In this example, we used this function to find the index position of a substring. Next, we are slicing the object from the start point (0) to that index point — something like Python substring before the character index position.

# Python substring Index Example
 
string = 'We are abc group working at abc company as a abc Developer';
 
end1 = string.index('bc') 
print(string[: end1])
 
end2 = string.index('group') 
print(string[: end2])
 
end3 = string.index('abc') 
print(string[: end3])
 
end4 = string.index('abc', 11) 
print(string[: end4])
 
end5 = string.index('abc', 35) 
print(string[: end5])

String substring using index function output

We are a
We are abc 
We are 
We are abc group working at 
We are abc group working at abc company as a 

Here, we are using the index position of a substring as the starting position. For instance, the substring after the character index position.

string = 'We are xyz group working at xyz company as a xyz Developer';
 
start1 = string.index('at') 
print(string[start1 : ])
print(string[0 : start1])
 
start2 = string.index('working') 
print(string[start2 : ])
 
start3 = string.index('xyz') 
print(string[start3 :])
 
start4 = string.index('xyz', 11) 
print(string[start4 :])
 
start5 = string.index('xyz', 35) 
print(string[start5 : ])

String substring using index function output

at xyz company as a xyz Developer
We are xyz group working 
working at xyz company as a xyz Developer
xyz group working at xyz company as a xyz Developer
xyz company as a xyz Developer
xyz Developer

Python substring find

You can use the find function to match or find the substring within a string. Or, you can use this Python substring string function to return a substring before Character or substring after character. In this example, we find the space within a string and return substring before space and after space.

# Python substring Find Example
 
string = 'Python Programming'
 
index_num = string.find(' ')
 
print('String Before the Space = ', string[ : index_num])
print('String After the Space = ', string[index_num : ])

String substring using a find function output

String Before the Space =  Python
String After the Space =   Programming

Here, we are using the second argument (starting point) to find the substring. Next, we are returning the substring before that character and after that character.

string = 'We are abc group working as a abc Developer in abc company';
 
end1 = string.find('group') 
print('Substring Before: ', string[: end1])
print('Substring After: ', string[end1 : ])
 
end2 = string.find('abc') 
print('\nSubstring Before: ', string[: end2])
print('Substring After: ', string[end2 : ])
 
end3 = string.find('abc', 11) 
print('\nSubstring Before: ', string[: end3])
print('Substring After: ', string[end3 : ])
 
end4 = string.find('abc', 35) 
print('\nSubstring Before: ', string[: end4])
print('Substring After: ', string[end4 : ])

String substring using a find function output

Substring Before:  We are abc 
Substring After:  group working as a abc Developer in abc company

Substring Before:  We are 
Substring After:  abc group working as a abc Developer in abc company

Substring Before:  We are abc group working as a 
Substring After:  abc Developer in abc company

Substring Before:  We are abc group working as a abc Developer in 
Substring After:  abc company

String substring count

Let us see how to count the occurrence of a substring in a python string. For this, we are using the Python count function.

# Python substring count Example
 
string = 'we are abc group working as a abc developer in abc company';
 
print('Number of Times Substring "a" Occurred : ', string.count('a'))
print('Number of Times Substring "o" Occurred : ', string.count('o'))
print('Number of Times Substring "abc" Occurred : ', string.count('abc'))

String substring count

Number of Times Substring "a" Occurred :  7
Number of Times Substring "o" Occurred :  4
Number of Times Substring "abc" Occurred :  3