Test if string in string python

How to Check if a Python String Contains Another String?

One of the most common operations that programmers use on strings is to check whether a string contains some other string.

If you are coming to Python from Java, for instance, you might have used the contains method to check if some substring exists in another string.

In Python, there are two ways to achieve this.

First: Using the in operator

The easiest way is via Python’s in operator.

Let’s take a look at this example.

>>> str = "Messi is the best soccer player" >>> "soccer" in str True >>> "football" in str False

As you can see, the in operator returns True when the substring exists in the string.

Otherwise, it returns false.

This method is very straightforward, clean, readable, and idiomatic.

Second: Using the find method

Another method you can use is the string’s find method.

Unlike the in operator which is evaluated to a boolean value, the find method returns an integer.

This integer is essentially the index of the beginning of the substring if the substring exists, otherwise -1 is returned.

Let’s see the find method in action.

>>> str = "Messi is the best soccer player" >>> str.find("soccer") 18 >>> str.find("Ronaldo") -1 >>> str.find("Messi") 0

One cool thing about this method is you can optionally specify a start index and an end index to limit your search within.

>>> str = "Messi is the best soccer player" >>> str.find("soccer", 5, 25) 18 >>> str.find("Messi", 5, 25) -1

Notice how a -1 was returned for “Messi” because you are limiting your search to the string between indices 5 and 25 only.

Python 3 Cheat Sheet for Beginners

Download a comprehensive cheat sheet for beginners with extensive code examples that covers all the topics that you need to learn.

Some Advanced Stuff

Assume for a second that Python has no built-in functions or methods that would check if a string contains another string.

How would you write a function to do that?

Well, an easy way is to brute force by checking if the substring exists starting from every possible position in the original string.

Читайте также:  Java android error log

For larger strings, this process can be really slow.

There are better algorithms for string searching.

I highly recommend this article from TopCoder if you want to learn more and dive deeper into string searching algorithms.

For more coverage of other string searching algorithms not covered in the previous article, this wikipedia page is great.

If you go through the previous articles and study them, your next question would be “well what algorithm does Python actually use?”

These kinds of questions almost always require digging into the source code.

But you are in luck because Python’s implementation is open source.

Perfect, I am happy the developers commented their code 🙂

It is very clear now that the find method uses a mix of boyer-moore and horspool algorithms.

Conclusion

You can use the in operator or the string’s find method to check if a string contains another string.

The in operator returns True if the substring exists in the string. Otherwise, it returns False.

The find method returns the index of the beginning of the substring if found, otherwise -1 is returned.

Python’s implementation (CPython) uses a mix of boyer-moore and horspool for string searching.

Learning Python?

Are you Beginning your Programming Career?

I provide my best content for beginners in the newsletter.

  • Python tips for beginners, intermediate, and advanced levels.
  • CS Career tips and advice.
  • Special discounts on my premium courses when they launch.

Источник

Python: Check if String Contains Substring

Checking whether a string contains a substring aids to generalize conditionals and create more flexible code. Additionally, depending on your domain model — checking if a string contains a substring may also allow you to infer fields of an object, if a string encodes a field in itself.

In this guide, we’ll take a look at how to check if a string contains a substring in Python.

The in Operator

The easiest way to check if a Python string contains a substring is to use the in operator.

The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring:

fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!") 

This operator is shorthand for calling an object’s __contains__ method, and also works well for checking if an item exists in a list. It’s worth noting that it’s not null-safe, so if our fullstring was pointing to None , an exception would be thrown:

TypeError: argument of type 'NoneType' is not iterable 

To avoid this, you’ll first want to check whether it points to None or not:

fullstring = None substring = "tack" if fullstring != None and substring in fullstring: print("Found!") else: print("Not found!") 

The String.index() Method

The String type in Python has a method called index() that can be used to find the starting index of the first occurrence of a substring in a string.

Читайте также:  Aspose words word to html

If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block:

fullstring = "StackAbuse" substring = "tack" try: fullstring.index(substring) except ValueError: print("Not found!") else: print("Found!") 

This method is useful if you also need to know the position of the substring, as opposed to just its existence within the full string. The method itself returns the index:

print(fullstring.index(substring)) # 1 

Though — for the sake of checking whether a string contains a substring, this is a verbose approach.

The String.find() Method

The String class has another method called find() which is more convenient to use than index() , mainly because we don’t need to worry about handling any exceptions.

If find() doesn’t find a match, it returns -1, otherwise it returns the left-most index of the substring in the larger string:

Free eBook: Git Essentials

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!

fullstring = "StackAbuse" substring = "tack" if fullstring.find(substring) != -1: print("Found!") else: print("Not found!") 

Naturally, it performs the same search as index() and returns the index of the start of the substring within the parent string:

print(fullstring.find(substring)) # 1 

Regular Expressions (RegEx)

Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. With Regular Expressions, you can perform flexible and powerful searches through much larger search spaces, rather than simple checks, like previous ones.

Python is shipped with a built-in module for regular expressions, called re . The re module contains a function called search() , which we can use to match a substring pattern:

from re import search fullstring = "StackAbuse" substring = "tack" if search(substring, fullstring): print "Found!" else: print "Not found!" 

This method is best if you are needing a more complex matching function, like case insensitive matching, or if you’re dealing with large search spaces. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.

About the Author

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.

Читайте также:  Python requests packages urllib3

Источник

Python check if string contains another string

Python check if string contains another string

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

String manipulation is a common task in any programming language. Python provides two common ways to check if a string contains another string.

Python check if string contains another string

Python string supports in operator. So we can use it to check if a string is part of another string or not. The in operator syntax is:

It returns True if “sub” string is part of “str”, otherwise it returns False . Let’s look at some examples of using in operator in Python.

str1 = 'I love Python Programming' str2 = 'Python' str3 = 'Java' print(f'"" contains "" = ') print(f'"" contains "" = ') print(f'"" contains "" = ') if str2 in str1: print(f'"" contains ""') else: print(f'"" does not contain ""') 
"I love Python Programming" contains "Python" = True "I love Python Programming" contains "python" = False "I love Python Programming" contains "Java" = False "I love Python Programming" contains "Python" 

python check if string contains another string using in operator

If you are not familiar with f-prefixed strings in Python, it’s a new way for string formatting introduced in Python 3.6. You can read more about it at f-strings in Python. When we use in operator, internally it calls __contains__() function. We can use this function directly too, however it’s recommended to use in operator for readability purposes.

s = 'abc' print('s contains a =', s.__contains__('a')) print('s contains A =', s.__contains__('A')) print('s contains X =', s.__contains__('X')) 
s contains a = True s contains A = False s contains X = False 

Using find() to check if a string contains another substring

We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

str1 = 'I love Python Programming' str2 = 'Python' str3 = 'Java' index = str1.find(str2) if index != -1: print(f'"" contains ""') else: print(f'"" does not contain ""') index = str1.find(str3) if index != -1: print(f'"" contains ""') else: print(f'"" does not contain ""') 
"I love Python Programming" contains "Python" "I love Python Programming" does not contain "Java" 

python check if a string contains a substring

You can checkout complete python script and more Python examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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