Method 1: Use the in keyword (the simplest)
Check whether the substring exists directly through the in operator:
text = "Hello, welcome to Python world." keyword = "Python" if keyword in text: print(f"Include keywords '{keyword}'") else: print(f"不Include keywords '{keyword}'")
Method 2: Use the () method
find() returns the start index of the substring (returns -1 if not found):
text = "Hello, welcome to Python world." keyword = "Python" if (keyword) != -1: print("Keywords exist") else: print("Keyword does not exist")
Method 3: Use the () method
Similar to find(), but a ValueError exception is thrown when not found:
try: index = (keyword) print(f"Keywords in index {index} Where") except ValueError: print("Keyword does not exist")
Method 4: Regular Expressions (Complex Matches)
Use the re module to achieve more flexible matching (such as ignoring case, fuzzy matching, etc.):
import re text = "Hello, welcome to Python world." pattern = r"python" # Regular expression pattern if (pattern, text, ): # Ignore case print("Keywords exist") else: print("Keyword does not exist")
Extended scenario
1. Check whether multiple keywords exist
Use any() to combine generator expressions:
keywords = ["Python", "Java", "C++"] text = "I love Python programming." if any(k in text for k in keywords): print("Contain at least one keyword")
2. Statistics the number of times keywords appear
use ():
count = ("Python") print(f"The keyword appears {count} Second-rate")
Knowledge extension
7 ways to determine whether a string contains a specific substring
We often encounter this requirement:Determine whether a string contains a certain keyword, that is, a specific substring
. For example, find the title of the book that contains "python" from a bunch of books.
It's very simple to determine that two strings are equal, it's straightforward==That's it. In fact, it is also very easy to determine the inclusion of substrings, and there is more than one way to do it. Let's share it with you below7A method that can achieve this effect:
1. Use in and not in
inandnot inexistPythonUniversity is a very common keyword, and we classify them as member operators.
Using these two member operators allows us to intuitively and clearly determine whether an object is in another object. The example is as follows:
>>> "llo" in "hello, python" True >>> >>> "lol" in "hello, python" False
2. Use the find method
Use string objectfindMethod, if a substring is found, it can return the location of the specified substring in the string. If it is not found, it can return-1
>>> "hello, python".find("llo") != -1 True >>> "hello, python".find("lol") != -1 False >>
3. Use the index method
There is a string objectindexMethods can return the index of the specified substring for the first time in the string. If it is not found, an exception will be thrown. Therefore, you need to pay attention to capture when using it.
def is_in(full_str, sub_str): try: full_str.index(sub_str) return True except ValueError: return False print(is_in("hello, python", "llo")) # True print(is_in("hello, python", "lol")) # False
4. Use the count method
Utilize andindexWe can also use this idea of saving the country through curvecountto judge.
As long as the result is greater than0This means that the substring exists in the string.
def is_in(full_str, sub_str): return full_str.count(sub_str) > 0 print(is_in("hello, python", "llo")) # True print(is_in("hello, python", "lol")) # False
5. Through magical methods
In the first method, we useinandnot inDetermine whether a substring exists in another character, actually when you use itinandnot inhour,PythonThe interpreter will check whether the object has__contains__
Magic method.
If there is, execute it, if there is noPythonIt will automatically iterate over the entire sequence, and return as long as the required item is found.True 。
Examples are as follows;
>>> "hello, python".__contains__("llo") True >>> >>> "hello, python".__contains__("lol") False >>>
This usage and usageinandnot inThere is no difference, but it is not ruled out that someone will write it like this to increase the difficulty of understanding the code.
6. With the help of operator
operatorModule ispythonThe built-in operator function interface in it defines some arithmetic and functions that compare built-in operations.operatorThe module is usedcImplemented, so the execution speed ratiopythonFast code.
existoperatorThere is a method incontainsIt is easy to determine whether the substring is in the string.
>>> import operator >>> >>> ("hello, python", "llo") True >>> ("hello, python", "lol") False >>>
7. Use regular matching
Speaking of search function, regularity can definitely be said to be a professional tool, and no matter how complex search rules are, they can satisfy you.
To determine whether a string exists in another string, using regularity is simply a waste of use.
import re def is_in(full_str, sub_str): if (sub_str, full_str): return True else: return False print(is_in("hello, python", "llo")) # True print(is_in("hello, python", "lol")) # False
Summarize
Recommended to use the in operator: simple and efficient, suitable for most scenarios.
Regular expression: suitable for scenarios where fuzzy matching (such as case insensitive, pattern matching).
Avoid redundant code: prioritize direct judgment logic (such as if keyword in text).
This is the article about 4 ways to determine whether a string contains keywords. For more related python to determine whether a string contains keywords, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!