Python string contains words

Python String Contains – See if String Contains a Substring

An easy way to check if a string contains a particular phrase is by using an if . in statement. We can do this as follows:

Today we’ll take a look at the various options you’ve got for checking if a string contains a substring. We’ll start by exploring the use of if . in statements, followed by using the find() function. Towards the end, there is also a section on employing regular expressions (regex) with re.search() to search strings.

Option 1: if . in

The example above demonstrated a quick way to find a substring within another string using an if . in statement. The statement will return True if the string does contain what we’re looking for and False if not. See below for an extension of the example used previously:

The output displays that our if . in statement looking for ‘apples’ only returned True for the first item in strings , which is correct.

It’s worth mentioning that if . in statements are case-sensitive. The line if ‘apples’ in string: wouldn’t detect ‘Apples’ . One way of correcting this is by using the lower() method, which converts all string characters into lowercase.

Читайте также:  Php выполнить exe файл

We can utilize the lower() method with the change below:

Alternatively, we could use the upper() function to search for ‘APPLES’ instead.

The if .. in approach has the fastest performance in most cases. It also has excellent readability, making it easy for other developers to understand what a script does.

Of the three options listed in this article, using if . in is usually the best approach for seeing if a string contains a substring. Remember that the simplest solution is quite often the best one!

Option 2: find()

Another option you’ve got for searching a string is using the find() method. If the argument we provide find() exists in a string, then the function will return the start location index of the substring we’re looking for. If not, then the function will return -1. The image below shows how string characters are assigned indexes:

We can apply find() to the first if . in example as follows:

For the first list item, ‘apples’ started at index 16, so find(‘apples’) returns 16. ‘apples’ isn’t in the string for the other two items, so find(‘apples’) returns -1.

The index() function can be used similarly and will also return the starting index of its argument. The disadvantage of using index() is that it will throw ValueError: substring not found if Python can’t find the argument. The find() and index() functions are also both case-sensitive.

Regex is short for regular expression, which is kind of like its own programming language. Through re.search , a regex search, we can determine if a string matches a pattern. The re.search() function generates a Match object if the pattern makes a match.

Looking at the Match object, span gives us the start and end index for ‘apples’ . Slicing the string using ‘This string has apples'[16:22] returns the substring ‘apples’ . The match field shows us the part of the string that was a match, which can be helpful when searching for a range of possible substrings that meet the search conditions.

We can access the span and match attributes using the span() and group() methods, as follows:

If the substring isn’t a match, we get the null value None instead of getting a Match object. See the example below for how we can apply regex to the string problem we’ve been using:

In this case, the if statement determines if re.search() returns anything other than None .

We could argue that regex might be overkill for a simple functionality like this. But something like the example above is a great starting point for regex, which has plenty of other capabilities.

For instance, we could change the first argument of the search() function to ‘apples|oranges’ , where | is the «OR» logical operator. In this context re.search() would return a match object for any strings with the substring ‘apples’ or ‘oranges’ .

The following demonstrates an example of this:

Summary

The easiest and most effective way to see if a string contains a substring is by using if . in statements, which return True if the substring is detected. Alternatively, by using the find() function, it’s possible to get the index that a substring starts at, or -1 if Python can’t find the substring. REGEX is also an option, with re.search() generating a Match object if Python finds the first argument within the second one.

Источник

Python String Contains – Python 3 Substring Tutorial

Dionysia Lemonaki

Dionysia Lemonaki

Python String Contains – Python 3 Substring Tutorial

In this article, you will learn how to check if a string contains a substring in Python.

Checking if a string contains a substring comes in handy when you have received user input and want your program to behave a certain way – or even when you want to replace one word with another.

Python offers many ways to confirm whether a substring is present in a string, and in this quick guide, you will see a few of them in action.

Here is what we will cover:

How to Check if a String Contains a Substring Using the in Operator in Python

Using the in operator is one of the clearest, most readable, and most Pythonic ways to confirm whether a substring is present in a string.

Therefore, the in operator is the preferred way of checking that a string contains a substring.

The general syntax for using the in operator is the following:

The in operator returns a Boolean value. A Boolean value is either True or False .

The in operator returns True if the substring is present in the string and False if the substring is not present.

>>> learn_coding = "You can learn to code for free!" >>> "free" in learn_coding True 

In the example above, I entered Python’s interactive console, also known as the Python interpreter or Python shell.

You can enter it after installing Python locally, opening your terminal, and typing Python or Python3 depending on your system.

I store the phrase You can learn to code for free! in a variable called learn_coding .

Then, I check to see if the substring free is present in the phrase You can learn to code for free! using the in operator.

Since the substring is present, in returns True .

It is important to note that the in operator only checks if the substring is present and exists in the string. It doesn’t check the position of the substring, nor does it give any information on how many times the substring appears in the string.

As a side note, you can also choose to check if a substring is not present in a string by using the not in operator:

>>> learn_coding = "You can learn to code for free!" >>> "free" not in learn_coding False 

This time, I use the not in operator to check whether the substring free is not present in the string You can learn to code for free! . Since free is present, the not in operator returns False .

Now, let’s go back to the in operator.

You can use the in operator to control the behavior of your program by setting conditions.

Let’s take the following example:

user_input = input("Do you need to pay to learn to code?: ") if "yes" in user_input: print("Wrong! You can learn to code for free!!") 

In the example above, I am asking a user for input and storing their answer in a variable named user_input .

Then, I use a conditional statement paired with the in operator to make a decision (if you need a refresher on conditional statements in Python, read this article).

If their answer contains the substring yes , then in returns the phrase Wrong! You can learn to code for free because the code in the if statement executes:

Do you need to pay to learn to code?: yes, I think you do Wrong! You can learn to code for free!! 

In the example above, the string the user entered, yes, I think you do , contains the substring yes and the code in the if block runs.

What happens when the user enters Yes, I think you do with a capital Y instead of a lowercase one?

Do you need to pay to learn to code?: Yes, I think you do 

As you see, nothing happens! The program has no output because Python strings are case-sensitive.

You could write an else statement to solve this. However, you could instead account for case sensitivity when checking to see if a substring is present in a string.

Let’s see how to do that in the following section.

In the section above, you saw that when searching if a substring is present in a string, the search is case-sensitive.

So, how can you make the search case insensitive?

You can convert the whole user input into lowercase by using the .lower() method:

user_input = input("Do you need to pay to learn to code?: ").lower() if "yes" in user_input: print("Wrong! You can learn to code for free!!") 

Now, when the user enters Yes with a capital Y , the code in the if statement runs, even if you were searching for the substring yes with a lowercase y . This is because you converted the user input text to all lowercase letters.

How to Check if a String Contains a Substring Using the .index() Method in Python

You can use the .index() Python method to find the starting index number of the first character of the first occurrence of a substring inside a string:

learn_coding = "You can learn to code for free! Yes, for free!" substring = "free" print(learn_coding.index(substring)) # output # 26 

In the example above, I stored the string You can learn to code for free! Yes, for free! in a variable named learn_coding .

I also stored the substring free in the variable substring .

Then, I called the .index() method on the string and passed the substring as the argument to find where the first free substring occurrence appears. (The string stored in learn_coding contains two instances of the substring free ).

Finally, I printed the result.

If the substring is not present in the string, then a ValueError: substring not found error gets raised:

learn_coding = "You can learn to code for free! Yes, for free!" substring = "paid" print(learn_coding.index(substring)) # output # Traceback (most recent call last): # File "main.py", line 4, in # print(learn_coding.index(substring)) # ValueError: substring not found 

The .index() method comes in handy when you want to know the location of the substring you are searching for and where the substring occurs and starts in the string.

The in operator lets you know whether the substring exists in the string, whereas the .index() method also tells you where it exists.

That said, .index() is not ideal when Python can’t find the substring in the string because it raises a ValueError error.

If you want to avoid that error from being raised when searching for a string, and you don’t want to use the in operator, you can use the Python find() method instead.

How to Check if a String Contains a Substring Using the .find() Method in Python

The .find() method works similarly to the .index() method — it checks to see if a string contains a substring, and if the substring is present, it returns its starting index.

learn_coding = "You can learn to code for free! Yes, for free!" substring = "free" print(learn_coding.find(substring)) # output # 26 

The difference between the .find() method and the .index() method is that with .find() , you don’t have to worry when it comes it handling exceptions, in comparison to .index() .

As you saw in the section above, when the string doesn’t contain the substring, index() raises an error.

On the other hand, when you are using the .find() method and the string doesn’t contain the substring you are searching for, .find() returns -1 without raising an exception:

learn_coding = "You can learn to code for free! Yes, for free!" substring = "paid" print(learn_coding.find(substring)) # output # -1 

Conclusion

Hopefully, this article helped you understand how to check if a string contains a substring in Python.

To learn more about the Python programming language, check out freeCodeCamp’s Python certification.

You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

Thank you for reading, and happy coding!

Источник

Оцените статью