- Python String Contains – See if String Contains a Substring
- Option 1: if . in
- Option 2: find()
- Option 3: Regex search()
- Summary
- Строка Python содержит: проверьте, содержит ли строка подстроку
- Методы проверки, содержит ли строка Python подстроку
- Строка Python содержит
- Пример использования метода String __contains__()
- Пример 1
- Пример 2
- Избегайте использования метода String __contains__()
- Заключение
- Python String contains: Check if String Contains Substring
- Methods to check if a Python String Contains a Substring
- Python String contains
- Example of using String __contains__() Method
- Example 1
- Example 2
- Avoid using String __contains__() Method
- Conclusion
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.
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.
Option 3: Regex search()
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.
Строка Python содержит: проверьте, содержит ли строка подстроку
В Python много раз, когда вы работаете с подстроками, вы хотите определить, находится ли подстрока внутри другой строки или нет, для этого может быть много причин, таких как поиск и фильтрация данных, проверка ввода и т. д. Для этого Python предоставляет нам с простым и эффективным методом для выполнения этой задачи.
В этой статье будут показаны различные встроенные функции для проверки наличия в строке подстроки в Python. Основная функция, которой мы уделяем основное внимание в этой статье, — это метод Python __contains__(), так что давайте начнем.
Методы проверки, содержит ли строка Python подстроку
Python предлагает множество способов проверить, содержит ли строка другие подстроки или нет. Некоторые из них приведены ниже:
- Использование метода find()
- Использование оператора in
- Использование метода index()
- Использование регулярного выражения
- Использование строки __contains__()
Оператор «in», методы find() и index() часто используются разработчиками для проверки подстроки в строке, и мы прикрепили ссылку к нашему руководству по каждому вышеупомянутому строковому методу, чтобы вы могли их прочитать. тоже, но в этом уроке мы будем использовать встроенную функцию __contains__().
Строка Python содержит
Строковая функция Python __contains__() может использоваться со строковым объектом, она принимает подстроку в качестве аргумента и возвращает True, если подстрока присутствует в строке.
string.__contains__(substring)
Здесь подстрока — это строка, которую вы хотите найти, а строка — это строковый объект, в котором вы хотите искать.
Возвращаться:
Тип возвращаемого значения этой функции — логическое значение, либо True, либо False, в зависимости от того, найдена ли подстрока в указанной строке.
Пример использования метода String __contains__()
Давайте рассмотрим несколько примеров того, как проверить, содержит ли строка подстроку в Python.
Пример 1
str = "Hello World!" sub_str = "World" if (str.__contains__(sub_str)): print("String contains Substring") else: print("String does not contain Substring")
Здесь мы указали строку, а затем подстроку, обе содержащие какой-либо символ, а затем мы использовали оператор if и использовали метод string.__contains__(), который возвращает True, если указанная нами подстрока присутствует в строке, и если поэтому оператор внутри оператора if будет выполняться, в противном случае будет выполнен оператор внутри оператора else.
String contains Substring
Поскольку «Мир» является подстрокой исходной строки «Hello World!», возвращаемое значение равно True и выполняется оператор if.
Пример 2
Попробуем проверить наличие подстроки «мир».
str = "Hello World!" sub_str = "world" if (str.__contains__(sub_str)): print("String contains Substring") else: print("String does not contain Substring")
String does not contain Substring
Этот метод чувствителен к регистру, поэтому строка «мир» считается отличной от строки «Мир», поэтому он возвращает False, и выполняется оператор внутри блока else.
Избегайте использования метода String __contains__()
Логики программирования, запрещающей использование метода __contains__(), нет, но есть несколько причин, по которым его использовать не рекомендуется.
Ниже приведены некоторые причины, по которым вам следует избегать использования __contains__ :
- Читаемость кода: ясно, что там, где другой метод выглядит читабельным, метод __contains__ выглядит сложным.
- Ограниченная функциональность: этот метод может проверять только одну строку, он не может выполнять сложные операции со строками.
- Не подходит для сложных структур данных: метод __contains__ не может правильно работать со сложными структурами данных, имеющими несколько уровней вложенности, или объектами со сложными отношениями.
- Альтернативы: Другая причина в том, что существует множество альтернатив, о которых мы упоминали в начале этого руководства, которые более надежны и похожи на этот метод, поэтому нет смысла его использовать.
Заключение
В этой статье мы научились использовать метод string.__contains__(), чтобы узнать, присутствует ли подстрока внутри строки или нет, если подстрока найдена, она возвращает True, если подстрока не найдена, она возвращает False. Это не лучший способ проверить, появляется ли подстрока в строке, но он самый быстрый. Надеюсь, вам понравилось читать этот урок.
Python String contains: Check if String Contains Substring
In Python, many times when you’re working with substrings you want to find whether a substring is inside another string or not, there can be many reasons for that like searching and filtering data, input validation, etc. For this, Python provides us with a simple and efficient method to accomplish this task.
This article will show you the various built-in functions to check if a string contains a substring in Python. The main function that is our main focus for this article is Python’s __contains__() method, so let’s get started.
Methods to check if a Python String Contains a Substring
Python offers many ways to check whether a String contains other substrings or not. Some of them are given below:
The ‘in’ operator, find(), and index() methods are frequently used to check for a substring within a string by developers and we have attached the link to our tutorial on each above-mentioned string method so that you can read them too, but for this tutorial, we will be using the built-in function __contains__().
Python String contains
The Python string __contains__() function can be used with a string object, it takes a substring as an argument and returns True if the substring is present in the string.
string.__contains__(substring)
Here, substring is the string you want to search, and string is the string object in which you want to search.
The return type of this function is a boolean value, it is either True or False, depending on whether the substring is found on the specified string.
Example of using String __contains__() Method
Let’s look at some examples of how to check whether a string contains a substring in Python.
Example 1
str = "Hello World!" sub_str = "World" if (str.__contains__(sub_str)): print("String contains Substring") else: print("String does not contain Substring")
Here we have specified a string, and then a substring, both containing some character, and then we have used the if statement and used the string.__contains__() method which returns True if the substring we specified is present in the string, and if so the statement inside the if statement will execute otherwise the statement inside the else statement will execute.
String contains Substring
Since “World” is a substring of the original string, “Hello World!”, the return value is True and the if statement is executed.
Example 2
Let’s try to check for the substring “world”.
str = "Hello World!" sub_str = "world" if (str.__contains__(sub_str)): print("String contains Substring") else: print("String does not contain Substring")
String does not contain Substring
This method is case sensitive, so the string “world” is considered different from the string “World”, hence it returns False, and the statement inside the else block is executed.
Avoid using String __contains__() Method
There is no programming logic that prohibits the use of the __contains__() method, but there are some reasons why it is not recommended to use it.
Below are some reasons why you should avoid using __contains__ :
- Code Readability: Well, it is clear that where other method looks readable, the __contains__ method looks complicated.
- Limited Functionality: This method can only check a single string, it is not able to perform complex string operations.
- Not suitable for complex data structures: The __contains__ method is not able to work properly with complex data structures having multiple levels of nesting or objects with complex relationships.
- Alternatives: Another reason is that there are many alternatives, which we have mentioned at the beginning of this tutorial, which are more reliable and similar to this method, so there is no point in using it.
Conclusion
In this article, we learned to use string.__contains__() method to find whether a substring is present inside a string or not, if the substring is found it returns True, if the substring is not found it returns False. It is not the best way to check whether a substring appears in the string but it is the fastest. Hope you enjoyed reading this tutorial.