Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python strings
python
substring

How to get substring in Python

Educative Answers Team

There are three methods in Python to check if a string contains another string.

1. Use find

The find method checks if the string contains a substring. If it does, the method returns the starting index of a substring within the string; otherwise it returns -1.

Syntax

The general syntax is :

string.find(substring)
a_string="Python Programming" 
substring1="Programming" 
substring2="Language" 
print("Check if "+a_string+" contains "+substring1+":")
print(a_string.find(substring1)) 
print("Check if "+a_string+" contains "+substring2+":")
print(a_string.find(substring2))

This function returns the starting index of the first matching instance so we can use this function for reversing or removing a unique word from a string.

2. Use the in operator

The in operator returns true if the substring exists in a string and false if ​otherwise.

Syntax

The general syntax is:

substring in string
a_string="Python Programming"
substring1="Programming"
substring2="Language"
print("Check if "+a_string+" contains "+substring1+":")
print(substring1 in a_string)
print("Check if "+a_string+" contains "+substring2+":")
print(substring2 in a_string)

This function just returns the boolean value so it can be used where we don’t need the starting index or count of the substring. Usually, we use this function in conditional statements.

3. Use count

The count method returns the number of occurrences of a substring in the string. If the substring is not found in a string, the function returns 0.

Syntax

The general syntax is :

string.count(substring)
a_string="Python Programming"
substring1="Programming"
substring2="Language"
print("Check if "+a_string+" contains "+substring1+":")
print(a_string.count(substring1))
print("Check if "+a_string+" contains "+substring2+":")
print(a_string.count(substring2))

This function returns the number of occurrences of a substring and it doesn’t return the starting index of each occurrence. Usually, it is used for word count.

RELATED TAGS

python strings
python
substring
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring