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
A but doesn't contain
a. So the latter message is printed. Most programming languages including Python distinguish the uppercase and lowercase letter.
How can we get the position or index of substring in a string? For example, the index of
The find() returns the position of a substring. If the string doesn't have the argument string, it returns -1.
Python so its index is -1. We can check the substring exisitence to use this method as follows.
Use of Counter
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
c['r'] is 0.