Tutorial

Python String Substring

Published on August 4, 2022
author

Pankaj

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.

Let’s first look at two different ways to create a substring.

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:]
print(name)

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

Output:

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

python string create substring using slice and split

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. python string contains substring

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

python string substring count

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] python string list of substring indexes positions

You can checkout complete python script and more Python examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2019

program executed,but the list is not printed

- nitin

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 9, 2019

    Thanks for the examples and explanations, are great.

    - Jorge

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.