Python string contains another string

Python поиск в строке

Проверка, содержит ли строка какую-нибудь другую строку, это одна из самых распространенных операций, осуществляемых разработчиками.

Если вы раньше (до перехода на Python) писали код, скажем, на Java, для подобной проверки вы могли использовать метод contains.

В Python есть два способа достичь той же цели.

1. Использование оператора in

Самый простой способ проверить, содержится ли в строке другая строка, это использовать оператор Python in .

Давайте рассмотрим пример.

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

Как видите, оператор in возвращает True , если указанная подстрока является частью строки. В противном случае он возвращает False .

Этот метод очень простой, понятный, читаемый и идиоматичный.

2. Использование метода find

Также для проверки вхождения одной строки в другую можно использовать строковый метод find .

В отличие от оператора, возвращающего булево значение, метод find возвращает целое число.

Это число является по сути индексом начала подстроки, если она есть в указанной строке. Если этой подстроки в строке не содержится, метод возвращает -1 .

Давайте посмотрим, как работает метод find .

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

Что особенно хорошо в применении этого метода — вы можете при желании ограничить пределы поиска, указав начальный и конечный индекс.

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

Обратите внимание, что для подстроки «Messi» метод вернул -1 . Это произошло потому, что мы ограничили поиск в строке промежутком символов с индексами от 5-го до 25-го.

Более сложные способы

Представьте на минутку, что в Python нет никаких встроенных функций или методов, позволяющих проверить, входит ли одна строка в другую. Как бы вы написали функцию для этой цели?

Можно использовать брутфорс-подход и на каждой возможной позиции в строке проверять, начинается ли там искомая подстрока. Но для длинных строк этот процесс будет очень медленным.

Есть лучшие алгоритмы поиска строк. Если вы хотите углубиться в эту тему, можем порекомендовать статью «Rabin-Karp and Knuth-Morris-Pratt Algorithms». Также вам может пригодиться статья «Поиск подстроки» в Википедии.

Если вы прочитаете указанные статьи, у вас может родиться закономерный вопрос: так какой же алгоритм используется в Python?

Для поиска ответов на подобные вопросы практически всегда нужно углубиться в исходный код. В этом плане вам повезло: Python это технология с открытым кодом. Давайте же в него заглянем.

Python поиск в строке

Как удачно, что разработчики прокомментировали свой код! Теперь нам совершенно ясно, что метод find использует смесь алгоритмов Бойера-Мура и Бойера-Мура-Хорспула.

Читайте также:  Php call method with array

Заключение

Для проверки, содержится ли указанная строка в другой строке, в Python можно использовать оператор in или метод find .

Оператор in возвращает True , если указанная подстрока является частью другой строки. В противном случае он возвращает False .

Метод find возвращает индекс начала подстроки в строке, если эта подстрока там есть, или -1 — если подстрока не найдена.

CPython использует для поиска строк комбинацию алгоритмов Бойера-Мура и Бойера-Мура-Хорспула.

Источник

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

Источник

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.

Читайте также:  Using php with wordpress

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.

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.
Читайте также:  Discord slash commands php

Источник

Python поиск в строке

Проверка, содержит ли строка какую-нибудь другую строку, это одна из самых распространенных операций, осуществляемых разработчиками.

Если вы раньше (до перехода на Python) писали код, скажем, на Java, для подобной проверки вы могли использовать метод contains.

В Python есть два способа достичь той же цели.

1. Использование оператора in

Самый простой способ проверить, содержится ли в строке другая строка, это использовать оператор Python in .

Давайте рассмотрим пример.

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

Как видите, оператор in возвращает True , если указанная подстрока является частью строки. В противном случае он возвращает False .

Этот метод очень простой, понятный, читаемый и идиоматичный.

2. Использование метода find

Также для проверки вхождения одной строки в другую можно использовать строковый метод find .

В отличие от оператора, возвращающего булево значение, метод find возвращает целое число.

Это число является по сути индексом начала подстроки, если она есть в указанной строке. Если этой подстроки в строке не содержится, метод возвращает -1 .

Давайте посмотрим, как работает метод find .

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

Что особенно хорошо в применении этого метода — вы можете при желании ограничить пределы поиска, указав начальный и конечный индекс.

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

Обратите внимание, что для подстроки «Messi» метод вернул -1 . Это произошло потому, что мы ограничили поиск в строке промежутком символов с индексами от 5-го до 25-го.

Более сложные способы

Представьте на минутку, что в Python нет никаких встроенных функций или методов, позволяющих проверить, входит ли одна строка в другую. Как бы вы написали функцию для этой цели?

Можно использовать брутфорс-подход и на каждой возможной позиции в строке проверять, начинается ли там искомая подстрока. Но для длинных строк этот процесс будет очень медленным.

Есть лучшие алгоритмы поиска строк. Если вы хотите углубиться в эту тему, можем порекомендовать статью «Rabin-Karp and Knuth-Morris-Pratt Algorithms». Также вам может пригодиться статья «Поиск подстроки» в Википедии.

Если вы прочитаете указанные статьи, у вас может родиться закономерный вопрос: так какой же алгоритм используется в Python?

Для поиска ответов на подобные вопросы практически всегда нужно углубиться в исходный код. В этом плане вам повезло: Python это технология с открытым кодом. Давайте же в него заглянем.

Python поиск в строке

Как удачно, что разработчики прокомментировали свой код! Теперь нам совершенно ясно, что метод find использует смесь алгоритмов Бойера-Мура и Бойера-Мура-Хорспула.

Заключение

Для проверки, содержится ли указанная строка в другой строке, в Python можно использовать оператор in или метод find .

Оператор in возвращает True , если указанная подстрока является частью другой строки. В противном случае он возвращает False .

Метод find возвращает индекс начала подстроки в строке, если эта подстрока там есть, или -1 — если подстрока не найдена.

CPython использует для поиска строк комбинацию алгоритмов Бойера-Мура и Бойера-Мура-Хорспула.

Источник

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