Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Python String Substring

A substring is the part of a string. Python string provides various methods to create a substring, check if it contains a substring, index of substring etc. In this tutorial, we will look into various operations related to substrings.

Create a Python String Substring

We can create a substring using string slicing. We can use split() function to create a list of substrings based on specified delimiter.

s = 'My Name is Pankaj'

# create substring using slice
name = s[11:]
print(name)

# list of substrings using split
l1 = s.split()
print(l1)

Output:

Pankaj
['My', 'Name', 'is', 'Pankaj']

Python String Substring – Checking if Substring is Found

We can use in operator or find() function to check if substring is present in the string or not.

s = 'My Name is Pankaj'

if 'Name' in s:
    print('Substring found')

if s.find('Name') != -1:
    print('Substring found')

Note that find() function returns the index position of the substring if it’s found, otherwise it returns -1.

Count of Substring Occurrence

We can use count() function to find the number of occurrences of a substring in the string.

s = 'My Name is Pankaj'

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

s = 'This Is The Best Theorem'
print('Substring count =', s.count('Th'))

Output:

Substring count = 3
Substring count = 3

Find all Indexes of Substring

There is no built-in function to get the list of all the indexes for the substring. However, we can easily define one using find() function.

def find_all_indexes(input_str, substring):
    l2 = []
    length = len(input_str)
    index = 0
    while index < length:
        i = input_str.find(substring, index)
        if i == -1:
            return l2
        l2.append(i)
        index = i + 1
    return l2


s = 'This Is The Best Theorem'
print(find_all_indexes(s, 'Th'))

Output: [0, 8, 17]

Conclusion

By this, we have come to the end of this topic.

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!