Check if word is in string python

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.

Читайте также:  Создать таблицу php my admin

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.

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.

Источник

Check if a Word Exists in a String in Python

Check if a Word Exists in a String in Python

  1. Use the in Operator to Check if a Word Exists in a String in Python
  2. Use the String.find() Method to Check if a Word Exists in a String in Python
  3. Use the String.index() Method to Check if a Word Exists in a String in Python
  4. Use the search() Method to Check if a Word Exists in a String in Python

Suppose there exist a string «The weather is so pleasant today» . If we want to check if the word «weather» is present in the string or not, we have multiple ways to find out.

In this guide, we will look at the in operator, string.find() method, string.index() method, and regular expression(RegEx) .

Use the in Operator to Check if a Word Exists in a String in Python

One of the easiest ways of searching a word in a string or sequences like list, tuple, or arrays is through the in operator. It returns a boolean value when used in a condition.

It can be either true or false . If the specified word exists, the statement evaluates to true ; if the word does not exist, it evaluates to false .

This operator is case-sensitive . If we try to locate the word Fun in the following code, we will obtain the message Fun not found in the output.

#Python 3.x sentence = "Learning Python is fun" word = "fun" if word in sentence:  print(word, "found!") else:  print(word, "not found!") 

If we want to check for a word within a string without worrying about the case, we must convert the main string and the word to search in the lowercase. In the following code, we will check the word Fun .

#Python 3.x sentence = "Learning Python is fun" word = "Fun" if word.lower() in sentence.lower():  print(word, "found!") else:  print(word, "not found!") 

Use the String.find() Method to Check if a Word Exists in a String in Python

We can use the find() method with a string to check for a specific word. If the specified word exists, it will return the word’s left-most or starting index in the main string.

Else, it will simply return the index –1 . The find() method also counts the index of spaces . In the following code, we get the output 9 because 9 is the starting index of Python, the index of character P .

This method is also case-sensitive by default. If we check for the word python , it will return -1 .

#Python 3.x string = "Learning Python is fun" index=string.find("Python") print(index) 

Use the String.index() Method to Check if a Word Exists in a String in Python

index() is the same as the find() method. This method also returns the lowest index of the substring in the main string.

The only difference is that when the specified word or substring does not exist, the find() method returns the index –1, while the index() method raises an exception (value error exception) .

#Python 3.x mystring = "Learning Python is fun" print(mystring.index("Python")) 

Now we try to find a word that doesn’t exist in the sentence.

#Python 3.x mystring = "Learning Python is fun" print(mystring.index("Java")) 
#Python 3.x ValueError Traceback (most recent call last)  in ()  1 mystring = "Learning Python is fun" ----> 2 print(mystring.index("Java"))  ValueError: substring not found 

Use the search() Method to Check if a Word Exists in a String in Python

We can check for a specific word through pattern matching of strings through the search() method. This method is available in the re module.

The re here stands for Regular Expression . The search method accepts two arguments.

The first argument is the word to find, and the second one is the entire string. But this method works slower than the other ones.

#Python 3.x from re import search sentence = "Learning Python is fun" word = "Python" if search(word, sentence):  print(word, "found!") else:   print(word, "not found!") 

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

Related Article — Python String

Источник

Check if a String Contains Word in Python

Check if a String Contains Word in Python

This tutorial will introduce the method to find whether a specified word is inside a string variable or not in Python.

Check the String if It Contains a Word Through an if/in Statement in Python

If we want to check whether a given string contains a specified word in it or not, we can use the if/in statement in Python. The if/in statement returns True if the word is present in the string and False if the word is not in the string.

The following program snippet shows us how to use the if/in statement to determine whether a string contains a word or not:

string = "This contains a word" if "word" in string:  print("Found") else:  print("Not Found") 

We checked whether the string variable string contains the word word inside it or not with the if/in statement in the program above. This approach compares both strings character-wise; this means that it doesn’t compare whole words and can give us wrong answers, as demonstrated in the following example:

string = "This contains a word" if "is" in string:  print("Found") else:  print("Not Found") 

The output shows that the word is is present inside the string variable string . But, in reality, this is is just a part of the first word This in the string variable.

This problem has a simple solution. We can surround the word and the string variable with white spaces to just compare the whole word. The program below shows us how we can do that:

string = "This contains a word" if " is " in (" " + string + " "):  print("Found") else:  print("Not Found") 

In the code above, we used the same if/in statement, but we slightly altered it to compare only individual words. This time, the output shows no such word as is present inside the string variable.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Python String

Источник

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