How do you check if a substring is in a string python?
In this guide, we'll take a look at how to check if a string contains a substring in Python. As usual, each approach we'll cover has different pros and cons. Show
The in OperatorThe easiest way to check if a Python string contains a substring is to use the The
This operator is shorthand for calling an object's
To avoid this, you'll first want to check whether it points to
The String.index() MethodThe String type in Python has a method called Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it! If the substring is not found, a
This method is useful if you need to know the position of the substring, as opposed to just its existence within the full string. The String.find() MethodThe String type has another method called If
If you'd prefer to avoid the need to catch errors, then this method should be favored over Regular Expressions (RegEx)Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. Python is shipped with a built-in module for regular expressions, called
This method is best if you are needing a more complex matching function, like case insensitive matching. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases. This article was written by Jacob Stopak, a software consultant and developer with passion for helping others improve their lives through code. Jacob is the creator of Initial Commit - a site dedicated to helping curious developers learn how their favorite programs are coded. Its featured project helps people learn Git at the code level. If you’re new to programming or come from a programming language other than Python, you may be looking for the best way to check whether a string contains another string in Python. Identifying such substrings comes in handy when you’re working with text content from a file or after you’ve received user input. You may want to perform different actions in your program depending on whether a substring is present or not. In this tutorial, you’ll focus on the most Pythonic way to tackle this task, using the membership operator Finally, you’ll also learn how to find substrings in pandas columns. This is helpful if you need to search through data from a CSV file. You could use the approach that you’ll learn in the next section, but if you’re working with tabular data, it’s best to load the data into a pandas DataFrame and search for substrings in pandas. How to Confirm That a Python String Contains Another StringIf you need to check whether a string contains a substring, use Python’s membership operator >>>
The When you use
You can use this intuitive syntax in conditional statements to make decisions in your code: >>>
In this code snippet, you use the membership operator to check whether The membership operator However, what if you want to know more about the substring? If you read through the text stored in Which of these occurrences did Python find? Does capitalization make a difference? How often does the substring show up in the text? And what’s the location of these substrings? If you need the answer to any of these questions, then keep on reading. Generalize Your Check by Removing Case SensitivityPython strings are case sensitive. If the substring that you provide uses different capitalization than the same word in your text, then Python won’t find it. For example, if you check for the lowercase word >>>
Despite
the fact that the word secret appears multiple times in the title-case text Humans have a different approach to language than computers do. This is why you’ll often want to disregard capitalization when you check whether a string contains a substring in Python. You can generalize your substring check by converting the whole input text to lowercase: >>>
Converting your input text to lowercase is a common way to account for the fact that humans think of words that only differ in capitalization as the same word, while computers don’t. Now that you’ve converted the string to lowercase to avoid unintended issues stemming from case sensitivity, it’s time to dig further and learn more about the substring. Learn More About the SubstringThe membership operator Python provides many additonal string methods that allow you to check how many target substrings the string contains, to search for substrings according to elaborate conditions, or to locate the index of the substring in your text. In this section, you’ll cover some additional string methods that can help you learn more about the substring. By using If you need to know where in your string the substring occurs, then you can use >>>
When you call But what if you want to find other occurrences of the
substring? The >>>
When you pass a starting index that’s past the first occurrence of the substring, then Python searches starting from there. In this case, you get another match
and not a That means that the text contains the substring more than once. But how often is it in there? You can use >>>
You used You can inspect all the substrings by splitting your text at default word borders and printing the words to your terminal using a >>>
In this example, you use
Now that you can inspect all the substrings that Python identifies, you may notice that Python doesn’t care whether there are any characters after the substring That’s good to know, but what can you do if you want to place stricter conditions on your substring check? Find a Substring With Conditions Using RegexYou
may only want to match occurrences of your substring followed by punctuation, or identify words that contain the substring plus other letters, such as For such cases that require more involved string matching, you can use regular expressions, or regex, with Python’s For example, if you want to find all the words that start with >>>
The You can then access these attributes through methods on the >>>
These results give you a lot of flexibility to continue working with the matched substring. For example, you could search for only
the substrings that are followed by a comma ( >>>
There are two potential matches in your text, but you only matched the first result fitting your query. When you use To find all the matches using >>>
By using When you use a capturing group, you can specify which part of the match you want to keep in your list by wrapping that part in parentheses: >>>
By wrapping secret in parentheses, you defined a single capturing group. The Using If you want to keep that information around, then >>>
When
you use You may notice that the punctuation shows up in these results even though you’re still using the capturing group. That’s because the string representation of a But the >>>
By calling You can go into much more detail with your substring matching when you use regular expressions. Instead of just checking whether a string contains another string, you can search for substrings according to elaborate conditions. Using regular expressions with Find a Substring in a pandas DataFrame ColumnIf you work with data that doesn’t come from a plain text file or from user input, but from a CSV file or an Excel sheet, then you could use the same approach as discussed above. However, there’s a better way to identify which cells in a column contain a substring: you’ll use pandas! In this example, you’ll work with a CSV file that contains fake company names and slogans. You can download the file below if you want to work along: When you’re working with tabular data in Python,
it’s usually best to load it into a pandas >>>
In this code block, you loaded a CSV file that contains one thousand rows of fake company data into a pandas DataFrame and inspected the first five rows using After you’ve loaded the data into the DataFrame, you can quickly query the whole pandas column to filter for entries that contain a substring: >>>
You can use When you’re working with >>>
In this code snippet, you’ve used the same pattern that you used earlier to match only words that contain secret but then continue with one or more word character ( You can write any complex regex pattern and pass it to
ConclusionLike a persistent treasure hunter, you found each You also learned how to descriptively use two other string methods, which are often misused to check for substrings:
After that, you explored how to find substrings according to more advanced conditions with regular expressions and a few functions in Python’s Finally, you also learned how you can use the DataFrame method You now know how to pick the most idiomatic approach when you’re working with substrings in Python. Keep using the most descriptive method for the job, and you’ll write code that’s delightful to read and quick for others to understand. How do you tell if a substring is in a string?You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
How do you check whether a string contains a substring in pandas?Using “contains” to Find a Substring in a Pandas DataFrame
The contains method returns boolean values for the Series with True for if the original Series value contains the substring and False if not. A basic application of contains should look like Series. str. contains("substring") .
How do you search for a specific part of a string in Python?String find() in Python
Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.
How do you check if a word is present in a string in Python?We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved.
|