Python trick operation: seven ways to determine whether a substring is included

There are many (and more and more) advanced features in the Python language, which are very popular among Python enthusiasts. In the eyes of these people, those who can write advanced features that ordinary developers can't understand are masters and great gods.

But you have to know that in teamwork, showing off skills is a taboo.

Why do you say that? Let me talk about my opinion:

  1. The simpler the code and the clearer the logic, the less error-prone;
  2. In teamwork, your code is not only maintained by you. It is a good moral to reduce the cost of reading/understanding the logic of the code.
  3. Simple code will only use the most basic syntactic sugar, and complex advanced features will have more dependencies (such as language version)

This article is the third content of the " Hyun Technology Series ". In this series, I will summarize and count the amazing operations I have seen. Here, if you are a Python enthusiast, you can learn some cool coding skills. At the same time, reading these contents may help you to read other people's code.

1. Use in and not in

inAnd not inin Python is very popular keywords, we will classify them as 成员运算符.

Using these two member operators, we can intuitively and clearly determine whether an object is in another object. Examples are as follows:

>>> "llo" in "hello, python"
True
>>>
>>> "lol" in "hello, python"
False

2. Use the find method

Using the find method of the string object, if a substring is found, it can return the position of the specified substring in the string, if not found, it will return -1

>>> "hello, python".find("llo") != -1
True
>>> "hello, python".find("lol") != -1
False
>>

3. Use the index method

The string object has an index method, which can return the index of the first occurrence of the specified substring in the string. If it is not found, an exception will be thrown, so 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

Using the idea of ​​saving the country with the index curve, we can also use the count method to judge.

As long as the judgment result is greater than 0, it 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 magic methods

In the first method we use in judging and not in a sub-string exists in another character, when you actually use in and not in, Python interpreter will go to check whether the object has a __contains__magic method.

If there is one, execute it. If not, Python will automatically iterate the entire sequence and return True as long as it finds the required item.

Examples are as follows;

>>> "hello, python".__contains__("llo")
True
>>>
>>> "hello, python".__contains__("lol")
False
>>>

This usage is no different from using in and not in, but it does not rule out that someone will write it like this to increase the difficulty of understanding the code.

6. With the help of operator

The operator module is a built-in operator function interface in python, which defines some functions for arithmetic and comparison built-in operations. The operator module is implemented in c, so the execution speed is faster than python code.

There is a method in the operator containscan easily determine whether the substring in the string.

>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
True
>>> operator.contains("hello, python", "lol")
False
>>> 

7. Use regular matching

Speaking of the search function, the regular rule can definitely be said to be a professional tool, and how complex the search rules can satisfy you.

For the need to determine whether a string exists in another string, using regularity is simply overkill.

import re

def is_in(full_str, sub_str):
    if re.findall(sub_str, full_str):
        return True
    else:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

Guess you like

Origin blog.csdn.net/weixin_36338224/article/details/109187689