Planet Python

Real Python: How to Check if a Python String Contains a Substring

To check if a string contains another string in Python, use the in membership operator, which is the recommended method for confirming the presence of a substring within a string. The in operator is intuitive and readable, making it a straightforward way to evaluate substring existence. This operator returns a Boolean value, True if the substring is found and False if it's not. The in operator is case sensitive, so it won't find a substring if the capitalization is different. To generalize the check and remove case sensitivity, convert the input text to lowercase. Additionally, you can use string methods like .count() and .index() to gather more detailed information about substrings, such as their frequency and position. The .count() method counts occurrences of a substring, while the .index() method finds the first occurrence's position. For more complex substring searches, use regular expressions with the re module. When dealing with tabular data, pandas provides efficient tools for searching for substrings within DataFrame columns, specifically the .str.contains() method. Understanding these methods and tools enables you to effectively check for substrings in Python strings, catering to various needs from simple checks to complex data analysis. The in membership operator can be used in conditional statements to make decisions in your code. Python considers empty strings as a substring of any other string, so checking for the empty string in a string returns True.
favicon
realpython.com
realpython.com