Net-informations.com

Check if String Contains Substring in Python

Checking if a string contains a substring is one of the most common tasks in any programming language. Python offers many ways to check if a string contains a substring. The simplest and fastest way to check whether a string contains a substring or not in Python is using the "in" operator , which is used as a comparison operator . Some other Python methods such as find(), index(), count() etc. also help to Check if a string contains a substring.

Using Python's "in" operator

The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

output

Python "in" operator takes two arguments, one on the left and one on the right, and returns True if the left argument string is contained within the right argument string.

More on "in" operator


Python

Note: The "in" operator is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.

__contains__() function

Python String class has the __contains__() method that we can use to check if it contains another string or not. When we use Python "in" operator , internally it calls __contains__() function. The __contains__ method defines how instances of class behave when they appear at right side of in and not in operator. We can use this function directly too, but don't . Methods that start with underscores are considered semantically private , however it's recommended to use in operator for readability purposes.

Using Python's str.find() method

Another method you can use is the string.find() method . The find() method evaluate if the string contains a substring . If it does, the find() method returns the starting index of a substring within the string otherwise it returns -1 .

output

More on find() method


Python find() method

Using str.find() method is the less Pythonic way , but it's still accepted. It's longer and a little bit more confusing, but it still gets the job done.

Using Python Regular Expression

Regular expression is widely used for pattern matching . Python has a built-in package called re , which can be used to work with Regular Expressions . The re module contains a function called search() , it can be used to check if a string contains the specified search pattern .

example

output

Using str.count() method

If you want to count the number of occurrences of a specific substring in a string, then you can use Python count() method . If the substring is not found in a string, the function returns 0 .


Python count() method









net-informations.com (C) 2020    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About