Python substring

In Python, we don’t have an exclusive string function to find or return a substring. However, we have multiple options for extracting or returning a substring in the Python programming language.

In this section, we explain all the possible options to return a substring with examples. We use some built-in functions and functionalities to get or find the string substring in Python.

Python substring Example

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

String slicing

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 points 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

Slicing output

Tutorial Gateway
Tutor
utorial G
torial Gate
ial Gatewa

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

s2 = 'Learning this Program'
 
print(s2[:])
 
print(s2[: -5]) #  from 0
 
print(s2[1 : -10])
 
print(s2[2 : -13])
 
print(s2[4 : -1])
 
print(s2[3 : -4])
Learning this Program
Learning this Pr
earning th
arning
ning this Progra
rning this Pro

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

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

Functions

Instead of slicing the object every time, you can create a Python 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 first argument from the start to the 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 = 'Coding Examples'
 
print(sbs(s3, 1, 5))
 
print(sbs(s3, 2, 10))
 
print(sbs(s3, 3, 14))
odin
ding Exa
ing Example

We use the start point and length in the Python substring example. This function accepts a string and optional arguments start point and length.

def substr(st, start = None, length = None):
    return st[start : ][: length]
 
st = 'Learning this Programming Language'
 
print(substr(st))
 
print(substr(st, 3))
 
print(substr(st, 2, 19))
 
print(substr(st, length = 10))
Learning this Programming Language
rning this Programming Language
arning this Program
Learning t

It is a better approach than the above example.

def sbstr(st1, start = None, length = None):
    return st1[start : length]
 
st1 = 'Learn this Programming Language'
 
print(sbstr(st1))
 
print(sbstr(st1, 7))
 
print(sbstr(st1, 2, 19))
 
print(sbstr(st1, length = 15))
Learn this Programming Language
his Programming Language
arn this Programm
Learn this Prog

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

def strsub(st2, start, end, steps = 1):
    return st2[start : end : steps]
 
st2 = 'Learn Tableau PowerBI and SSIS  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))
earn
er
arn Tableau PowerBI and SSIS
a baPeInSS
LrTluor dS o
LnbuwIdIf

Python substring in reverse

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

str1 = 'Learn this Simple Programming Language'
 
print(str1[:: -1])
 
print(str1[19:: -1])
 
print(str1[4 :: -1])
 
print(str1[9 :: -1])
 
print(str1[11 :: -1])
egaugnaL gnimmargorP elpmiS siht nraeL
rP elpmiS siht nraeL
nraeL
siht nraeL
S siht nraeL

Using For Loop

You can also use for loop withthe range function to return it. For this, we have to use the print function along with the end argument. This example returns a sentence that starts at 3 and ends at 24.

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

Python substring slice

The slice function allows you to slice the given one and returns a substring. 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 English 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 English
earn English Languag
earn English Language for F
nglish Language for Fr

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

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

Python substring match

Check whether the word is present in the given string or not using the 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 = ', substr)
We found the Matching = Hello

This time, we are checking the non-existing word using if in the 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 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

This example shows how to return a text before the character. For this, we are using the built-in function called Split.

Here, we used the Python split function to split the given text into two substrings using space and 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 and after the 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

This Python example shows how to return a substring after a 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 = 'contact@tutorialgateway.org'
 
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 is used to find the index position of the given character. In this example, we used this function to find the index of the sub-string. Next, we slice the object from the start point (0) to that index point — something like text before the character starts at the 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 half string as the starting position. For instance, the Python substring 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 text before or after a character. In this example, we find the space or whitespace and return text before and after that.

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

Here, we use the second argument (starting point) to find the sentence. Next, we are returning the Python substring before that 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