How to check if a Python string contains the other string: find(), collections.Counter

In Python, you can check if a string contains the other string using the if statement.

s = 'Apple'

if 'p' in s:
    print('p is in Apple')
else:
    print('p is not in Apple')

# p is in Apple

It's so simple and the same as checking if a list contains an element. The if-in statement is often used in Python programming. Uppercase and lowercase letters are exactly ditinguished.

s = 'Apple'

if 'a' in s:
    print('a is in Apple')
else:
    print('a is not in Apple')

# a is not in Apple

Apple contains A but doesn't contain a. So the latter message is printed. Most programming languages including Python distinguish the uppercase and lowercase letter.

find()

How can we get the position or index of substring in a string? For example, the index of Script in JavaScript is 4 because there 4 letters before Script in JavaScript. You don't need to make the original function to get it.

s = "JavaScript"

a = s.find('Script')
b = s.find('Python')

print(a)  # 4
print(b)  # -1

The find() returns the position of a substring. If the string doesn't have the argument string, it returns -1. JavaScript doesn't have Python so its index is -1. We can check the substring exisitence to use this method as follows.

s = "JavaScript"

a = s.find('Script')

if 0 < s.find('Script'):
    print('Contained')
else:
    print('Not contained')

# Contained

Use of Counter

The Counter class from collections enables you to count a substring as well as checking its existence.

from collections import Counter

s = 'apple'
c = Counter(s)

print(type(c))  # <class 'collections.Counter'>

a = c['a']
p = c['p']
r = c['r']

print(a)  # 1
print(p)  # 2
print(r)  # 0

The Counter object is instantiated with a string and you can get the count of a substring by using square brackets. The zero count means the string doesn't have the substring. r is not in apple so c['r'] is 0.

Python String

Python Tutorial