Home > Article > Backend Development > How to determine whether a string contains a specified substring in Python
How does Python determine whether a string contains the specified string? This article will introduce to you three methods in Python to determine whether a string contains a specified substring. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
One of the most common operations programmers use on strings is to determine whether a string contains a specified substring. Python does this in a very easy to read and easy to implement way. There are 3 ways to do this.
First: Use the in operator
The easiest way is through python’s in operator.
in takes two "parameters", one on the left and one on the right. If the left parameter is included in the right parameter, it returns true.
Let’s take a look at this example:
>>> str = "Messi is the best soccer player" >>> result = "soccer" in str >>> print result True >>> result = "football" in str >>> print result False
As you can see, the in operator returns True when there is a substring in the string.
Otherwise, it returns false.
This approach is very simple, clean, readable and idiomatic.
Second: Use the find()/rfind() method of the string module
Another method you can also use is character String find method.
Unlike the in operator, which evaluates to a Boolean value, the find method returns an integer.
This integer is essentially the index of the start of the substring if the substring exists, otherwise -1 is returned.
Let’s see the find method in action.
>>> import string >>> str = "Messi is the best soccer player" >>> str.find("soccer") 18 >>> str.rfind("Ronaldo") -1 >>> str.find("Messi") 0
A great thing about this method: you can specify a start index and an end index to limit your search scope.
For example:
>>> import string >>> str = "Messi is the best soccer player" >>> str.find("soccer", 5, 25) 18 >>> str.find("Messi", 5, 25) -1
Note: When judging "Messi", if it returns -1, because you limit the search to the string between index 5 and 25 .
Third: Use the index()/rindex() method of the string module
##index()/rindex() method and find( )/rfind() methods are similar, except that a ValueError exception will be reported when the substring cannot be found.import string def find_string(s,t): try: string.index(s,t) return True except(ValueError): return False s='nihao,shijie' t='nihao' result = find_string(s,t) print result #TrueSummary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to determine whether a string contains a specified substring in Python. For more information, please follow other related articles on the PHP Chinese website!