Skip to content

Python check if string contains substring

  • by

Using the in keyword you can check if a string contains a substring in Python. Python has the syntax built-in with the in keyword:

Python checks if a string contains the substring

Simple example code.

s = "Stack Abuse"
sb = "tack"

print(s in sb)
print("Stack" in s)

Output:

Python check if string contains substring

Another option you’ve got for searching for a string is to use the find() method.

strings = ['This string has apples', 'This string has oranges', 'This string has neither']

for s in strings:
    apples_index = s.find('apples')
    if apples_index < 0:
        print('Apples not in string')
    else:
        print(f'Apples in string starting at index {apples_index}')

Regex search()

With a regex search, we can determine if a string matches a pattern.

import re

re.search('apples', 'This string has apples')

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading