Python Substring examples

[Total: 1   Average: 5/5]

Create a 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:]

# list of substrings using split
l1 = s.split()
['My', 'Name', 'is', 'Pankaj']

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'))


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
        index = i + 1
    return l2

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


[0, 8, 17]










Leave a Reply

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages