A sequence of Unicode character(s) is called a string. It comprises a sequence of characters or a series that may contain special characters and alphanumeric. This article focuses on the concept of the substring in python and how it works. 

What Is a Substring in Python?

Part of a string is known as a substring. There are multiple methods for creating a substring in python and checking if a substring is present in a string, index of a substring, and more. Let us look at various operations related to substrings. 

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

How to Create a Substring

A substring can be created using many ways. One of the popular ways is string slicing. 

To create a list of substrings based on a specific delimiter present in a string, we use the split() function. 

A substring in python can be generated by slicing as follows:

string[begin: end: step]

where, 

begin: is the starting index of the substring. The substring includes this element. If begin is not mentioned while slicing, it is assumed as 0. 

Step:  is the character that has to be included after the current character. The default value of the step is one and is assumed as one if not mentioned. 

End: is the ending index of the substring. This element is excluded in the substring. It is assumed to be the same as the string's length if the value is not specified or the given value exceeds the string length. 

The syntax for slicing a string:

1. string[begin: end]: substring includes characters from start to end-1. Example:

s= 'substring in python.'

s[2:10]

Output: ‘bstring’

2. string[: end]: substring includes characters from start to end-1. Example for slicing without begin index:

s= ' substring in python.'

s[:7]

Output: 'substri

3. string[begin:]: substring includes characters from the begin index to the end of the string. Example for slicing without end index:

s= ‘substring in python.'

s[1:]

Output: ‘ubstring in python'

4. string[begin:end: step]: substring includes characters from start to end-1 excusing every step character. Example for slicing with step-index:

s= ‘substring in python'

s[2:10:2]

Output: ‘btig’

5. s[:]- substring includes the entire string. Example for slicing without begin or end index :

s= ‘substring in python'

s[:]

Output: 'usbstring in python'

6. s[index]: substring includes a single character. Example for getting character at a given index:

s= ‘substring in python'

s[1]

Output : ‘u’

7. Negative slicing- Use a negative index for getting a substring. Example:

s= ' substring in python '

s[0:-3]

Output: ‘substring in pyt’

8. Reversing a string- Slicing can be used to return the reverse of string using a negative step. Example:

s= 'substring in python'

s[::-1]

Output: ‘nohtyp ni gnirtsbus’

The output of all the above templates:

SubstringinPython_1

Code to demonstrate the creation of substring in python:

s= ' substring in python '

# create a substring using slicing

a = s[11:]

print(a)

# Create list of substrings using split function

b = s.split()

print(b)

Output:

SubstringinPython_2

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

How to Check if the Substring Is Found

find() function or the in operator is used to check if a substring is present in the given string or not. 

We can use in operator or find() function to check if the string's substring is present in the string. Here is an example 

s= ' substring in python '

if 'python' in s:

    print('Substring found')

if s.find('all') != -1:

    print('Substring found')

else:

     print('Substring not found')

Output:

SubstringinPython_3.

To find the number of occurrences of a given substring in the input string, use the count() function as follows: 

s = 'This is the count'

print('Substring count =', s.count('i'))

Output:

SubstringinPython_4

To find all indexes of substring in python, there is no inbuilt function. But we can define one using find() function to get the list of all indexes for a substring. Here’s how:

def indexes(string, substring):

    l = []

    length = len(string)

    index = 0

    while index < length:

        i = string.find(substring, index)

        if i == -1:

            return l

        l.append(i)

        index = i + 1

    return l

s = 'substring in python'

print(indexes(s, 'i'))

Output:

SubstringinPython_5

How to Get the Substring From a Given String Using List Slicing

When we are given a string, we can get the substring in python using list slicing. Here are a few examples:

1. Code to create a substring in python from a string 

# Initialise the string 

string = 'substring in python'

print ("Initial string: ", string) 

# creating substring from beginning

# define upto what index substring is needed 

start = string[:2] 

end = string[3:] 

#result 

print ("Resultant substring from start:", start) 

print ("Resultant substring from end:", end)

Output:

SubstringinPython_6

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

2. Create a substring by taking characters from a particular gap (step)

# Initialise string 

string = 'substring in python'

print ("Initial String: ", string) 

# create substring by taking element after certain position gap and define length upto which substring is required 

alt = string[::2] 

gap = string[::3] 

# result 

print ("Resultant substring from start:", alt) 

print ("Resultant substring from end:", gap)

Output:

SubstringinPython_7

3. Create a substring while considering string from the middle with some step gap between characters

# Initialise string 

string = 'substring in python'

print ("Initial string: ", string) 

# create substring by taking element after certain step gap in a defined length 

astring = string[2:11:2] 

# result 

print ("Resultant substring:", astring)

Output:

SubstringinPython_8

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

We have reached the end of the article on 'substring in python'. All the examples given above form an idea of how slicing works and how it helps create substrings of various types in python also check out our next tutorial on Queue in Python And if you wish to master python in and out, you can enroll in our Python Certification Course. Keep learning!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449