When you’re working with a Python program, you might need to search for and locate a specific string inside another string.
This is where Python’s built-in string methods come in handy.
In this article, you will learn how to use Python’s built-in find()
string method to help you search for a substring inside a string.
Here is what we will cover:
- Syntax of the
find()
method- How to use
find()
with no start and end parameters example - How to use
find()
with start and end parameters example - Substring not found example
- Is the
find()
method case-sensitive?
- How to use
find()
vsin
keywordfind()
vsindex()
The find()
Method — A Syntax Overview
The find()
string method is built into Python’s standard library.
It takes a substring as input and finds its index — that is, the position of the substring inside the string you call the method on.
The general syntax for the find()
method looks something like this:
string_object.find("substring", start_index_number, end_index_number)
Let’s break it down:
string_object
is the original string you are working with and the string you will call thefind()
method on. This could be any word you want to search through.- The
find()
method takes three parameters – one required and two optional. "substring"
is the first required parameter. This is the substring you are trying to find insidestring_object
. Make sure to include quotation marks.start_index_number
is the second parameter and it’s optional. It specifies the starting index and the position from which the search will start. The default value is0
.end_index_number
is the third parameter and it’s also optional. It specifies the end index and where the search will stop. The default is the length of the string.- Both the
start_index_number
and theend_index_number
specify the range over which the search will take place and they narrow the search down to a particular section.
The return value of the find()
method is an integer value.
If the substring is present in the string, find()
returns the index, or the character position, of the first occurrence of the specified substring from that given string.
If the substring you are searching for is not present in the string, then find()
will return -1
. It will not throw an exception.
How to Use find()
with No Start and End Parameters Example
The following examples illustrate how to use the find()
method using the only required parameter – the substring you want to search.
You can take a single word and search to find the index number of a specific letter:
fave_phrase = "Hello world!"
# find the index of the letter 'w'
search_fave_phrase = fave_phrase.find("w")
print(search_fave_phrase)
#output
# 6
I created a variable named fave_phrase
and stored the string Hello world!
.
I called the find()
method on the variable containing the string and searched for the letter ‘w’ inside Hello world!
.
I stored the result of the operation in a variable named search_fave_phrase
and then printed its contents to the console.
The return value was the index of w
which in this case was the integer 6
.
Keep in mind that indexing in programming and Computer Science in general always starts at 0
and not 1
.
How to Use find()
with Start and End Parameters Example
Using the start and end parameters with the find()
method lets you limit your search.
For example, if you wanted to find the index of the letter ‘w’ and start the search from position 3
and not earlier, you would do the following:
fave_phrase = "Hello world!"
# find the index of the letter 'w' starting from position 3
search_fave_phrase = fave_phrase.find("w",3)
print(search_fave_phrase)
#output
# 6
Since the search starts at position 3, the return value will be the first instance of the string containing ‘w’ from that position and onwards.
You can also narrow down the search even more and be more specific with your search with the end parameter:
fave_phrase = "Hello world!"
# find the index of the letter 'w' between the positions 3 and 8
search_fave_phrase = fave_phrase.find("w",3,8)
print(search_fave_phrase)
#output
# 6
Substring Not Found Example
As mentioned earlier, if the substring you specify with find()
is not present in the string, then the output will be -1
and not an exception.
fave_phrase = "Hello world!"
# search for the index of the letter 'a' in "Hello world"
search_fave_phrase = fave_phrase.find("a")
print(search_fave_phrase)
# -1
Is the find()
Method Case-Sensitive?
What happens if you search for a letter in a different case?
fave_phrase = "Hello world!"
#search for the index of the letter 'W' capitalized
search_fave_phrase = fave_phrase.find("W")
print(search_fave_phrase)
#output
# -1
In an earlier example, I searched for the index of the letter w
in the phrase «Hello world!» and the find()
method returned its position.
In this case, searching for the letter W
capitalized returns -1
– meaning the letter is not present in the string.
So, when searching for a substring with the find()
method, remember that the search will be case-sensitive.
The find()
Method vs the in
Keyword – What’s the Difference?
Use the in
keyword to check if the substring is present in the string in the first place.
The general syntax for the in
keyword is the following:
substring in string
The in
keyword returns a Boolean value – a value that is either True
or False
.
>>> "w" in "Hello world!"
True
The in
operator returns True
when the substring is present in the string.
And if the substring is not present, it returns False
:
>>> "a" in "Hello world!"
False
Using the in
keyword is a helpful first step before using the find()
method.
You first check to see if a string contains a substring, and then you can use find()
to find the position of the substring. That way, you know for sure that the substring is present.
So, use find()
to find the index position of a substring inside a string and not to look if the substring is present in the string.
The find()
Method vs the index()
Method – What’s the Difference?
Similar to the find()
method, the index()
method is a string method used for finding the index of a substring inside a string.
So, both methods work in the same way.
The difference between the two methods is that the index()
method raises an exception when the substring is not present in the string, in contrast to the find()
method that returns the -1
value.
fave_phrase = "Hello world!"
# search for the index of the letter 'a' in 'Hello world!'
search_fave_phrase = fave_phrase.index("a")
print(search_fave_phrase)
#output
# Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_article/demopython.py", line 4, in <module>
# search_fave_phrase = fave_phrase.index("a")
# ValueError: substring not found
The example above shows that index()
throws a ValueError
when the substring is not present.
You may want to use find()
over index()
when you don’t want to deal with catching and handling any exceptions in your programs.
Conclusion
And there you have it! You now know how to search for a substring in a string using the find()
method.
I hope you found this tutorial helpful.
To learn more about the Python programming language, check out freeCodeCamp’s Python certification.
You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce your understanding of the concepts you learned.
Thank you for reading, and happy coding!
Happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Часто нам нужно найти символ в строке python. Для решения этой задачи разработчики используют метод find()
. Он помогает найти индекс первого совпадения подстроки в строке. Если символ или подстрока не найдены, find возвращает -1.
Синтаксис
string.find(substring,start,end)
Метод find
принимает три параметра:
substring
(символ/подстрока) — подстрока, которую нужно найти в данной строке.start
(необязательный) — первый индекс, с которого нужно начинать поиск. По умолчанию значение равно 0.end
(необязательный) — индекс, на котором нужно закончить поиск. По умолчанию равно длине строки.
Параметры, которые передаются в метод, — это подстрока, которую требуются найти, индекс начала и конца поиска. Значение по умолчанию для начала поиска — 0, а для конца — длина строки.
В этом примере используем метод со значениями по умолчанию.
Метод find()
будет искать символ и вернет положение первого совпадения. Даже если символ встречается несколько раз, то метод вернет только положение первого совпадения.
>>> string = "Добро пожаловать!"
>>> print("Индекс первой буквы 'о':", string.find("о"))
Индекс первой буквы 'о': 1
Поиск не с начала строки с аргументом start
Можно искать подстроку, указав также начальное положение поиска.
В этом примере обозначим стартовое положение значением 8 и метод начнет искать с символа с индексом 8. Последним положением будет длина строки — таким образом метод выполнит поиска с индекса 8 до окончания строки.
>>> string = "Специалисты назвали плюсы и минусы Python"
>>> print("Индекс подстроки 'али' без учета первых 8 символов:", string.find("али", 8))
Индекс подстроки 'али' без учета первых 8 символов: 16
Поиск символа в подстроке со start и end
С помощью обоих аргументов (start
и end
) можно ограничить поиск и не проводить его по всей строке. Найдем индексы слова «пожаловать» и повторим поиск по букве «о».
>>> string = "Добро пожаловать!"
>>> start = string.find("п")
>>> end = string.find("ь") + 1
>>> print("Индекс первой буквы 'о' в подстроке:", string.find("о", start, end))
Индекс первой буквы 'о' в подстроке: 7
Проверка есть ли символ в строке
Мы знаем, что метод find()
позволяет найти индекс первого совпадения подстроки. Он возвращает -1
в том случае, если подстрока не была найдена.
>>> string = "Добро пожаловать!"
>>> print("Есть буква 'г'?", string.find("г") != -1)
Есть буква 'г'? False
>>> print("Есть буква 'т'?", string.find("т") != -1)
Есть буква 'т'? True
Поиск последнего вхождения символа в строку
Функция rfind()
напоминает find()
, а единое отличие в том, что она возвращает максимальный индекс. В обоих случаях же вернется -1
, если подстрока не была найдена.
В следующем примере есть строка «Добро пожаловать!». Попробуем найти в ней символ «о» с помощью методов find()
и rfind()
.
>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом rfind:", string.rfind("о"))
Поиск 'о' методом rfind: 11
Вывод показывает, что find()
возвращает индекс первого совпадения подстроки, а rfind()
— последнего совпадения.
Второй способ поиска — index()
Метод index()
помогает найти положение данной подстроки по аналогии с find()
. Единственное отличие в том, что index()
бросит исключение в том случае, если подстрока не будет найдена, а find()
просто вернет -1
.
Вот рабочий пример, показывающий разницу в поведении index()
и find()
:
>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом index:", string.index("о"))
Поиск 'о' методом index: 1
В обоих случаях возвращается одна и та же позиция. А теперь попробуем с подстрокой, которой нет в строке:
>>> string = "Добро пожаловать"
>>> print("Поиск 'г' методом find:", string.find("г"))
Поиск 'г' методом find: 1
>>> print("Поиск 'г' методом index:", string.index("г"))
Traceback (most recent call last):
File "pyshell#21", line 1, in module
print("Поиск 'г' методом index:", string.index("г"))
ValueError: substring not found
В этом примере мы пытались найти подстроку «г». Ее там нет, поэтому find()
возвращает -1, а index()
бросает исключение.
Поиск всех вхождений символа в строку
Чтобы найти общее количество совпадений подстроки в строке можно использовать ту же функцию find()
. Пройдемся циклом while по строке и будем задействовать параметр start
из метода find()
.
Изначально переменная start
будет равна -1, что бы прибавлять 1 у каждому новому поиску и начать с 0. Внутри цикла проверяем, присутствует ли подстрока в строке с помощью метода find.
Если вернувшееся значение не равно -1, то обновляем значением count.
Вот рабочий пример:
my_string = "Добро пожаловать"
start = -1
count = 0
while True:
start = my_string.find("о", start+1)
if start == -1:
break
count += 1
print("Количество вхождений символа в строку: ", count )
Количество вхождений символа в строку: 4
Выводы
- Метод
find()
помогает найти индекс первого совпадения подстроки в данной строке. Возвращает -1, если подстрока не была найдена. - В метод передаются три параметра: подстрока, которую нужно найти,
start
со значением по умолчанию равным 0 иend
со значением по умолчанию равным длине строки. - Можно искать подстроку в данной строке, задав начальное положение, с которого следует начинать поиск.
- С помощью параметров
start
иend
можно ограничить зону поиска, чтобы не выполнять его по всей строке. - Функция
rfind()
повторяет возможностиfind()
, но возвращает максимальный индекс (то есть, место последнего совпадения). В обоих случаях возвращается -1, если подстрока не была найдена. index()
— еще одна функция, которая возвращает положение подстроки. Отличие лишь в том, чтоindex()
бросает исключение, если подстрока не была найдена, аfind()
возвращает -1.find()
можно использовать в том числе и для поиска общего числа совпадений подстроки.
I’m working with Python, and I’m trying to find out if you can tell if a word is in a string.
I have found some information about identifying if the word is in the string — using .find
, but is there a way to do an if
statement. I would like to have something like the following:
if string.find(word):
print("success")
mkrieger1
18.2k4 gold badges53 silver badges64 bronze badges
asked Mar 16, 2011 at 1:10
0
What is wrong with:
if word in mystring:
print('success')
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Mar 16, 2011 at 1:13
fabrizioMfabrizioM
46.2k15 gold badges100 silver badges118 bronze badges
13
if 'seek' in 'those who seek shall find':
print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word — for example, 'word' in 'swordsmith'
is True. If you only want to match whole words, you ought to use regular expressions:
import re
def findWholeWord(w):
return re.compile(r'b({0})b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None
answered Mar 16, 2011 at 1:52
Hugh BothwellHugh Bothwell
55k8 gold badges84 silver badges99 bronze badges
6
If you want to find out whether a whole word is in a space-separated list of words, simply use:
def contains_word(s, w):
return (' ' + w + ' ') in (' ' + s + ' ')
contains_word('the quick brown fox', 'brown') # True
contains_word('the quick brown fox', 'row') # False
This elegant method is also the fastest. Compared to Hugh Bothwell’s and daSong’s approaches:
>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop
>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'b({0})b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop
>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop
Edit: A slight variant on this idea for Python 3.6+, equally fast:
def contains_word(s, w):
return f' {w} ' in f' {s} '
answered Apr 11, 2016 at 20:32
user200783user200783
13.6k12 gold badges68 silver badges132 bronze badges
6
You can split string to the words and check the result list.
if word in string.split():
print("success")
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Dec 1, 2016 at 18:26
CorvaxCorvax
7727 silver badges13 bronze badges
3
find returns an integer representing the index of where the search item was found. If it isn’t found, it returns -1.
haystack = 'asdf'
haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1
if haystack.find(needle) >= 0:
print('Needle found.')
else:
print('Needle not found.')
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Mar 16, 2011 at 1:13
Matt HowellMatt Howell
15.7k7 gold badges48 silver badges56 bronze badges
0
This small function compares all search words in given text. If all search words are found in text, returns length of search, or False
otherwise.
Also supports unicode string search.
def find_words(text, search):
"""Find exact words"""
dText = text.split()
dSearch = search.split()
found_word = 0
for text_word in dText:
for search_word in dSearch:
if search_word == text_word:
found_word += 1
if found_word == len(dSearch):
return lenSearch
else:
return False
usage:
find_words('çelik güray ankara', 'güray ankara')
answered Jun 22, 2012 at 22:51
Guray CelikGuray Celik
1,2811 gold badge14 silver badges13 bronze badges
0
If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:
def smart_find(haystack, needle):
if haystack.startswith(needle+" "):
return True
if haystack.endswith(" "+needle):
return True
if haystack.find(" "+needle+" ") != -1:
return True
return False
This assumes that commas and other punctuations have already been stripped out.
IanS
15.6k9 gold badges59 silver badges84 bronze badges
answered Jun 15, 2012 at 7:23
daSongdaSong
4071 gold badge5 silver badges9 bronze badges
1
Using regex is a solution, but it is too complicated for that case.
You can simply split text into list of words. Use split(separator, num) method for that. It returns a list of all the words in the string, using separator as the separator. If separator is unspecified it splits on all whitespace (optionally you can limit the number of splits to num).
list_of_words = mystring.split()
if word in list_of_words:
print('success')
This will not work for string with commas etc. For example:
mystring = "One,two and three"
# will split into ["One,two", "and", "three"]
If you also want to split on all commas etc. use separator argument like this:
# whitespace_chars = " tnrf" - space, tab, newline, return, formfeed
list_of_words = mystring.split( tnrf,.;!?'"()")
if word in list_of_words:
print('success')
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Dec 18, 2017 at 11:44
tstempkotstempko
1,1761 gold badge15 silver badges17 bronze badges
2
As you are asking for a word and not for a string, I would like to present a solution which is not sensitive to prefixes / suffixes and ignores case:
#!/usr/bin/env python
import re
def is_word_in_text(word, text):
"""
Check if a word is in a text.
Parameters
----------
word : str
text : str
Returns
-------
bool : True if word is in text, otherwise False.
Examples
--------
>>> is_word_in_text("Python", "python is awesome.")
True
>>> is_word_in_text("Python", "camelCase is pythonic.")
False
>>> is_word_in_text("Python", "At the end is Python")
True
"""
pattern = r'(^|[^w]){}([^w]|$)'.format(word)
pattern = re.compile(pattern, re.IGNORECASE)
matches = re.search(pattern, text)
return bool(matches)
if __name__ == '__main__':
import doctest
doctest.testmod()
If your words might contain regex special chars (such as +
), then you need re.escape(word)
answered Aug 9, 2017 at 10:11
Martin ThomaMartin Thoma
122k156 gold badges604 silver badges941 bronze badges
Advanced way to check the exact word, that we need to find in a long string:
import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock"
for m in re.finditer(r"bofb", text):
if m.group(0):
print("Present")
else:
print("Absent")
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Nov 2, 2016 at 8:39
RameezRameez
5545 silver badges11 bronze badges
What about to split the string and strip words punctuation?
w in [ws.strip(',.?!') for ws in p.split()]
If need, do attention to lower/upper case:
w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]
Maybe that way:
def wcheck(word, phrase):
# Attention about punctuation and about split characters
punctuation = ',.?!'
return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]
Sample:
print(wcheck('CAr', 'I own a caR.'))
I didn’t check performance…
answered Dec 26, 2020 at 5:18
marciomarcio
5367 silver badges19 bronze badges
You could just add a space before and after «word».
x = raw_input("Type your word: ")
if " word " in x:
print("Yes")
elif " word " not in x:
print("Nope")
This way it looks for the space before and after «word».
>>> Type your word: Swordsmith
>>> Nope
>>> Type your word: word
>>> Yes
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Feb 26, 2015 at 14:23
PyGuyPyGuy
433 bronze badges
1
I believe this answer is closer to what was initially asked: Find substring in string but only if whole words?
It is using a simple regex:
import re
if re.search(r"b" + re.escape(word) + r"b", string):
print('success')
Martin Thoma
122k156 gold badges604 silver badges941 bronze badges
answered Aug 25, 2021 at 13:25
Milos CuculovicMilos Cuculovic
19.5k50 gold badges159 silver badges264 bronze badges
One of the solutions is to put a space at the beginning and end of the test word. This fails if the word is at the beginning or end of a sentence or is next to any punctuation. My solution is to write a function that replaces any punctuation in the test string with spaces, and add a space to the beginning and end or the test string and test word, then return the number of occurrences. This is a simple solution that removes the need for any complex regex expression.
def countWords(word, sentence):
testWord = ' ' + word.lower() + ' '
testSentence = ' '
for char in sentence:
if char.isalpha():
testSentence = testSentence + char.lower()
else:
testSentence = testSentence + ' '
testSentence = testSentence + ' '
return testSentence.count(testWord)
To count the number of occurrences of a word in a string:
sentence = "A Frenchman ate an apple"
print(countWords('a', sentence))
returns 1
sentence = "Is Oporto a 'port' in Portugal?"
print(countWords('port', sentence))
returns 1
Use the function in an ‘if’ to test if the word exists in a string
answered Mar 18, 2022 at 9:37
iStuartiStuart
4054 silver badges6 bronze badges
В этой статье поговорим про строки в Python, особенности поиска, а также о том, как искать подстроку или символ в строке.
Но сначала давайте вспомним основные методы для обработки строк в Python:
• isalpha(str): если строка в Python включает в себя лишь алфавитные символы, возвращается True;
• islower(str): True возвращается, если строка включает лишь символы в нижнем регистре;
• isupper(str): True, если символы строки в Python находятся в верхнем регистре;
• startswith(str): True, когда строка начинается с подстроки str;
• isdigit(str): True, когда каждый символ строки — цифра;
• endswith(str): True, когда строка в Python заканчивается на подстроку str;
• upper(): строка переводится в верхний регистр;
• lower(): строка переводится в нижний регистр;
• title(): для перевода начальных символов всех слов в строке в верхний регистр;
• capitalize(): для перевода первой буквы самого первого слова строки в верхний регистр;
• lstrip(): из строки в Python удаляются начальные пробелы;
• rstrip(): из строки в Python удаляются конечные пробелы;
• strip(): из строки в Python удаляются и начальные, и конечные пробелы;
• rjust(width): когда длина строки меньше, чем параметр width, слева добавляются пробелы, строка выравнивается по правому краю;
• ljust(width): когда длина строки в Python меньше, чем параметр width, справа от неё добавляются пробелы для дополнения значения width, при этом происходит выравнивание строки по левому краю;
• find(str[, start [, end]): происходит возвращение индекса подстроки в строку в Python. В том случае, если подстрока не найдена, выполняется возвращение числа -1;
• center(width): когда длина строки в Python меньше, чем параметр width, слева и справа добавляются пробелы (равномерно) для дополнения значения width, причём происходит выравнивание строки по центру;
• split([delimeter[, num]]): строку в Python разбиваем на подстроки в зависимости от разделителя;
• replace(old, new[, num]): в строке одна подстрока меняется на другую;
• join(strs): строки объединяются в одну строку, между ними вставляется определённый разделитель.
Обрабатываем строку в Python
Представим, что ожидается ввод числа с клавиатуры. Перед преобразованием введенной нами строки в число можно легко проверить, введено ли действительно число. Если это так, выполнится операция преобразования. Для обработки строки используем такой метод в Python, как isnumeric():
string = input("Введите какое-нибудь число: ") if string.isnumeric(): number = int(string) print(number)Следующий пример позволяет удалять пробелы в конце и начале строки:
string = " привет мир! " string = string.strip() print(string) # привет мир!Так можно дополнить строку пробелами и выполнить выравнивание:
print("iPhone 7:", "52000".rjust(10)) print("Huawei P10:", "36000".rjust(10))В консоли Python будет выведено следующее:
iPhone 7: 52000 Huawei P10: 36000Поиск подстроки в строке
Чтобы в Python выполнить поиск в строке, используют метод find(). Он имеет три формы и возвращает индекс 1-го вхождения подстроки в строку:
• find(str): поиск подстроки str производится с начала строки и до её конца;
• find(str, start): с помощью параметра start задаётся начальный индекс, и именно с него и выполняется поиск;
• find(str, start, end): посредством параметра end задаётся конечный индекс, поиск выполняется до него.
Когда подстрока не найдена, метод возвращает -1:
welcome = "Hello world! Goodbye world!" index = welcome.find("wor") print(index) # 6 # ищем с десятого индекса index = welcome.find("wor",10) print(index) # 21 # ищем с 10-го по 15-й индекс index = welcome.find("wor",10,15) print(index) # -1Замена в строке
Чтобы в Python заменить в строке одну подстроку на другую, применяют метод replace():
• replace(old, new): подстрока old заменяется на new;
• replace(old, new, num): параметр num показывает, сколько вхождений подстроки old требуется заменить на new.Пример замены в строке в Python:
phone = "+1-234-567-89-10" # дефисы меняются на пробелы edited_phone = phone.replace("-", " ") print(edited_phone) # +1 234 567 89 10 # дефисы удаляются edited_phone = phone.replace("-", "") print(edited_phone) # +12345678910 # меняется только первый дефис edited_phone = phone.replace("-", "", 1) print(edited_phone) # +1234-567-89-10Разделение на подстроки в Python
Для разделения в Python используется метод split(). В зависимости от разделителя он разбивает строку на перечень подстрок. В роли разделителя в данном случае может быть любой символ либо последовательность символов. Этот метод имеет следующие формы:
• split(): в роли разделителя применяется такой символ, как пробел;
• split(delimeter): в роли разделителя применяется delimeter;
• split(delimeter, num): параметром num указывается, какое количество вхождений delimeter применяется для разделения. При этом оставшаяся часть строки добавляется в перечень без разделения на подстроки.Соединение строк в Python
Рассматривая простейшие операции со строками, мы увидели, как объединяются строки через операцию сложения. Однако есть и другая возможность для соединения строк — метод join():, объединяющий списки строк. В качестве разделителя используется текущая строка, у которой вызывается этот метод:
words = ["Let", "me", "speak", "from", "my", "heart", "in", "English"] # символ разделителя - пробел sentence = " ".join(words) print(sentence) # Let me speak from my heart in English # символ разделителя - вертикальная черта sentence = " | ".join(words) print(sentence) # Let | me | speak | from | my | heart | in | EnglishА если вместо списка в метод join передать простую строку, разделитель будет вставляться уже между символами:
word = "hello" joined_word = "|".join(word) print(joined_word) # h|e|l|l|o
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.
Syntax: str_obj.find(sub, start, end)
Parameters:
- sub: Substring that needs to be searched in the given string.
- start (optional): Starting position where the substring needs to be checked within the string.
- end (optional): End position is the index of the last value for the specified range. It is excluded while checking.
Return: Returns the lowest index of the substring if it is found in a given string. If it’s not found then it returns -1.
Python String find() method Examples
Python3
word
=
'geeks for geeks'
print
(word.find(
'for'
))
Output:
6
Note:
- If the start and end indexes are not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
- The find() method is similar to index(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
find() With No start and end Argument
When the find() function is called without specifying the start and end arguments, it searches for the first occurrence of the substring within the entire input string from the beginning to the end.
Python3
word
=
'geeks for geeks'
result
=
word.find(
'geeks'
)
print
(
"Substring 'geeks' found at index:"
, result)
result
=
word.find(
'for'
)
print
(
"Substring 'for ' found at index:"
, result)
if
word.find(
'pawan'
) !
=
-
1
:
print
(
"Contains given substring "
)
else
:
print
(
"Doesn't contains given substring"
)
Output:
Substring 'geeks' found at index: 0 Substring 'for ' found at index: 6 Doesn't contains given substring
Explanation :
In the code, We are finding the word geeks in the string “geeks for geeks” with the find() function of Python. The First Find() function is returning the index of the first geeks word found in the string “geeks for geeks”, which is the index 0. The Second Find() function is returning the index of the first for word found in the string “geeks for geeks”, which is index 6. In the end, we are finding the pawan in the string “geeks for geeks”, which is not there so the find() function is returning -1 and according to the condition, the output Doesn’t contains given substring.
find() With start and end Arguments
When the find() function is called with the start and/or end arguments, it searches for the first occurrence of the substring within the specified portion of the input string, delimited by the start and/or end indices.
Python3
word
=
'geeks for geeks'
print
(word.find(
'ge'
,
2
))
print
(word.find(
'geeks '
,
2
))
print
(word.find(
'g'
,
4
,
10
))
print
(word.find(
'for '
,
4
,
11
))
Output:
10 -1 -1 6
find() Total Occurrences of a Substring
find() function can be used to count the total occurrences of a word in a string.
Python3
main_string
=
"Hello, hello, Hello, HELLO! , hello"
sub_string
=
"hello"
count_er
=
0
start_index
=
0
for
i
in
range
(
len
(main_string)):
j
=
main_string.find(sub_string,start_index)
if
(j!
=
-
1
):
start_index
=
j
+
1
count_er
+
=
1
print
(
"Total occurrences are: "
, count_er)
Output :
Total occurrences are: 2
Last Updated :
18 Apr, 2023
Like Article
Save Article