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 sub string 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 this programming language, you can slice any object to return a portion of the object. In this example, we use the slicing concept to return a Python substring. Slicing accepts three arguments, and they are the start and stop point and steps.

s1 = 'Tutorial Gateway'
 
print(s1[:]) # returns complete characters
 
print(s1[: 5]) # From 0 to 5
 
print(s1[1 : 10])
 
print(s1[2 : 13])
 
print(s1[5 : 15]) # 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 numbers as well to get the substring. In this example, we are using Negative index as the endpoint. Negative index mean, it counts from rightmost sequence of characters to the left. It means, print(string[2 : -13]) returns substring from 2 to end -13 (removes rightmost 13 characters).

s2 = 'Learn Python Tutorial'
 
print(s2[:])
 
print(s2[: -5]) #  from 0
 
print(s2[1 : -10])
 
print(s2[2 : -13])
 
print(s2[4 : -1])
 
print(s2[3 : -4])
Learn Python Tutorial
Learn Python Tut
earn Pytho
arn Py
n Python Tutoria
rn Python Tuto

In this Python substring example, we are using the third value inside the slicing. It can help you to skip the characters. 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 String and Functions in Python.

string = 'Python Programming Language for Free'
 
print(string[:])
 
print(string[0 : 14]) # is equal to print([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 Python 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 first argument from start to endpoint and returns the result. Please refer to Functions and Types of Functions to understand the function creation and types

def sbs(s3, start, end):
    return s3[start:end]
 
s3 = 'Python Programming'
 
print(sbs(s3, 1, 5))
 
print(sbs(s3, 2, 10))
 
print(sbs(s3, 3, 14))
ytho
thon Pro
hon Program

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

def substr(st, start = None, length = None):
    return st[start : ][: length]
 
st = 'Learn Python Programming Language'
 
print(substr(st))
 
print(substr(st, 3))
 
print(substr(st, 2, 19))
 
print(substr(st, length = 10))
Learn Python Programming Language
rn Python Programming Language
arn Python Programm
Learn Pyth

It is a better approach than the above Python substring example.

def substr(st1, start = None, length = None):
    return st1[start : length]
 
st1 = 'Learn Python Programming Language'
 
print(substr(st1))
 
print(substr(st1, 7))
 
print(substr(st1, 2, 19))
 
print(substr(st1, length = 15))
Learn Python Programming Language
ython Programming Language
arn Python Progra
Learn Python Pr

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

def strsub(st2, start, end, steps = 1):
    return st2[start : end : steps]
 
st2 = 'Python Programming Language for Free'
 
print(strsub(st2, 1, 5))
print(strsub(st2, 1, 5, 2))
 
print(strsub(st2, 2, 30))
print(strsub(st2, 2, 30, 3))
 
print(strsub(st2, 0, 35, 3))
print(strsub(st2, 0, 35, 4))
ytho
yh
thon Programming Language fo
tnrrmgaueo
Ph oai na rr
PoranaafF

Python substring in reverse

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

str1 = 'Learn Python Programming Language'
 
print(str1[:: -1])
 
print(str1[19:: -1])
 
print(str1[4 :: -1])
 
print(str1[9 :: -1])
 
print(str1[11 :: -1])
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 example returns a sentence starts at 3 and ends at 24.

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

Python substring slice

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

str3 = 'Learn Python Language for Free'
 
sub1 = slice(4)
print(str3[sub1])
 
sub2 = slice(3, 13)
print(str3[sub2])
 
sub3 = slice(1, 21)
print(str3[sub3])
 
sub4 = slice(1, 28)
print(str3[sub4])
 
sub5 = slice(7, 29)
print(str3[sub5])
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.

str4 = 'Learn Python Language for Free'
 
sub1 = slice(-1, -7, -1)
print(str4[sub1])
 
sub2 = slice(-7, 3, -1)
print(str4[sub2])
eerF r
of egaugnaL nohtyP n

Python substring match

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

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

This time, we are checking the non-existing word using if in operator

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

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

str5 = 'We are abc working at abc company'
 
subst = 'abc'
 
if str5.find(subst) == -1:
    print('We haven\'t found what you are looking for = ', subst)
else:
    print('We found the Matching = ', subst)
We found the Matching = 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 function called Python Split. 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.

c = 'Tutorial Gateway'
 
first, second = c.split(' ')
 
print('Before Character space = ', first)
Before Character space = Tutorial

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

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

after Character

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

d = 'Hello World!'
 
first, second = d.split(' ')
 
print('Before the Space = ', first)
print('After the Space = ', second)
Before the Space =  Hello
After the Space =  World!

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

e = '[email protected]'
 
name, domain = e.split('@')
 
print('Before Character @ = ', name)
print('After Character @ = ', domain)
Before Character @ =  contact
After Character @ =  tutorialgateway.org

Python substring Index

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

f = 'We are abc group working at abc company as a abc Developer';
 
end1 = f.index('bc') 
print(f[: end1])
 
end2 = f.index('group') 
print(f[: end2])
 
end3 = f.index('abc') 
print(f[: end3])
 
end4 = f.index('abc', 11) 
print(f[: end4])
 
end5 = f.index('abc', 35) 
print(f[: end5])
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 halfstring as the starting position. For instance, the sub string after the character index position.

g = 'We are xyz group working at xyz company as a xyz Developer';
 
start1 = g.index('at') 
print(g[start1 : ])
print(g[0 : start1])
 
start2 = g.index('working') 
print(g[start2 : ])
 
start3 = g.index('xyz') 
print(g[start3 :])
 
start4 = g.index('xyz', 11) 
print(g[start4 :])
 
start5 = g.index('xyz', 35) 
print(g[start5 : ])
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 method

You can use the find function to match or find the character within a string. Next, you can use this Python string slicing to return a sub string before Character or after character. In this example, we find the space or whitespace and return sub string before and after that.

h = 'Python Programming'
 
index_num = h.find(' ')
 
print('Before the Space = ', h[ : index_num])
print('After the Space = ', h[index_num : ])
Before the Space =  Python
After the Space =   Programming

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

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

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

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

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

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

j = 'we are abc group working as a abc developer in abc company';
 
print('Number of Times "a" Occurred : ', j.count('a'))
print('Number of Times "o" Occurred : ', j.count('o'))
print('Number of Times "abc" Occurred : ', j.count('abc'))
Number of Times "a" Occurred :  7
Number of Times "o" Occurred :  4
Number of Times "abc" Occurred :  3