Как найти все символы в строке python

There is no simple built-in string function that does what you’re looking for, but you could use the more powerful regular expressions:

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

If you want to find overlapping matches, lookahead will do that:

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]

re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you’re only iterating through the results once.

David Leon's user avatar

answered Jan 12, 2011 at 2:43

moinudin's user avatar

moinudinmoinudin

133k45 gold badges189 silver badges214 bronze badges

9

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

Thus, we can build it ourselves:

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]

No temporary strings or regexes required.

Pratik Deoghare's user avatar

answered Jan 12, 2011 at 3:13

Karl Knechtel's user avatar

Karl KnechtelKarl Knechtel

61.6k11 gold badges97 silver badges147 bronze badges

6

Here’s a (very inefficient) way to get all (i.e. even overlapping) matches:

>>> string = "test test test test"
>>> [i for i in range(len(string)) if string.startswith('test', i)]
[0, 5, 10, 15]

answered Jan 12, 2011 at 2:48

thkala's user avatar

thkalathkala

83.5k23 gold badges155 silver badges199 bronze badges

3

Use re.finditer:

import re
sentence = input("Give me a sentence ")
word = input("What word would you like to find ")
for match in re.finditer(word, sentence):
    print (match.start(), match.end())

For word = "this" and sentence = "this is a sentence this this" this will yield the output:

(0, 4)
(19, 23)
(24, 28)

answered Feb 3, 2016 at 19:01

Idos's user avatar

IdosIdos

15k14 gold badges59 silver badges73 bronze badges

2

Again, old thread, but here’s my solution using a generator and plain str.find.

def findall(p, s):
    '''Yields all the positions of
    the pattern p in the string s.'''
    i = s.find(p)
    while i != -1:
        yield i
        i = s.find(p, i+1)

Example

x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]

returns

[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]

answered Dec 23, 2015 at 23:09

AkiRoss's user avatar

AkiRossAkiRoss

11.6k6 gold badges59 silver badges85 bronze badges

3

You can use re.finditer() for non-overlapping matches.

>>> import re
>>> aString = 'this is a string where the substring "is" is repeated several times'
>>> print [(a.start(), a.end()) for a in list(re.finditer('is', aString))]
[(2, 4), (5, 7), (38, 40), (42, 44)]

but won’t work for:

In [1]: aString="ababa"

In [2]: print [(a.start(), a.end()) for a in list(re.finditer('aba', aString))]
Output: [(0, 3)]

AnukuL's user avatar

AnukuL

5751 gold badge7 silver badges21 bronze badges

answered Jan 12, 2011 at 2:55

Chinmay Kanchi's user avatar

Chinmay KanchiChinmay Kanchi

62.2k22 gold badges86 silver badges114 bronze badges

2

Come, let us recurse together.

def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""

    substring_length = len(substring)    
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]

No need for regular expressions this way.

answered Nov 1, 2013 at 3:16

Cody Piersall's user avatar

Cody PiersallCody Piersall

8,2442 gold badges42 silver badges57 bronze badges

2

If you’re just looking for a single character, this would work:

string = "dooobiedoobiedoobie"
match = 'o'
reduce(lambda count, char: count + 1 if char == match else count, string, 0)
# produces 7

Also,

string = "test test test test"
match = "test"
len(string.split(match)) - 1
# produces 4

My hunch is that neither of these (especially #2) is terribly performant.

answered Sep 24, 2014 at 21:12

jstaab's user avatar

jstaabjstaab

3,31925 silver badges40 bronze badges

1

this is an old thread but i got interested and wanted to share my solution.

def find_all(a_string, sub):
    result = []
    k = 0
    while k < len(a_string):
        k = a_string.find(sub, k)
        if k == -1:
            return result
        else:
            result.append(k)
            k += 1 #change to k += len(sub) to not search overlapping results
    return result

It should return a list of positions where the substring was found.
Please comment if you see an error or room for improvment.

answered Apr 1, 2015 at 9:23

Thurines's user avatar

ThurinesThurines

1111 silver badge3 bronze badges

This does the trick for me using re.finditer

import re

text = 'This is sample text to test if this pythonic '
       'program can serve as an indexing platform for '
       'finding words in a paragraph. It can give '
       'values as to where the word is located with the '
       'different examples as stated'

#  find all occurances of the word 'as' in the above text

find_the_word = re.finditer('as', text)

for match in find_the_word:
    print('start {}, end {}, search string '{}''.
          format(match.start(), match.end(), match.group()))

answered Jul 6, 2018 at 9:34

Bruno Vermeulen's user avatar

Bruno VermeulenBruno Vermeulen

2,8982 gold badges14 silver badges28 bronze badges

This thread is a little old but this worked for me:

numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"

marker = 0
while marker < len(numberString):
    try:
        print(numberString.index("five",marker))
        marker = numberString.index("five", marker) + 1
    except ValueError:
        print("String not found")
        marker = len(numberString)

wingerse's user avatar

wingerse

3,6301 gold badge28 silver badges57 bronze badges

answered Sep 1, 2014 at 12:48

Andrew H's user avatar

Andrew HAndrew H

46610 silver badges22 bronze badges

You can try :

>>> string = "test test test test"
>>> for index,value in enumerate(string):
    if string[index:index+(len("test"))] == "test":
        print index

0
5
10
15

answered Feb 27, 2018 at 6:44

Harsha Biyani's user avatar

Harsha BiyaniHarsha Biyani

7,0199 gold badges37 silver badges61 bronze badges

You can try :

import re
str1 = "This dress looks good; you have good taste in clothes."
substr = "good"
result = [_.start() for _ in re.finditer(substr, str1)]
# result = [17, 32]

answered Oct 25, 2021 at 10:13

Mohammad Amin Eskandari's user avatar

2

When looking for a large amount of key words in a document, use flashtext

from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)

Flashtext runs faster than regex on large list of search words.

answered Sep 28, 2018 at 17:29

Uri Goren's user avatar

Uri GorenUri Goren

13.2k6 gold badges57 silver badges109 bronze badges

This function does not look at all positions inside the string, it does not waste compute resources. My try:

def findAll(string,word):
    all_positions=[]
    next_pos=-1
    while True:
        next_pos=string.find(word,next_pos+1)
        if(next_pos<0):
            break
        all_positions.append(next_pos)
    return all_positions

to use it call it like this:

result=findAll('this word is a big word man how many words are there?','word')

answered Jan 13, 2020 at 12:39

Valentin Goikhman's user avatar

0

src = input() # we will find substring in this string
sub = input() # substring

res = []
pos = src.find(sub)
while pos != -1:
    res.append(pos)
    pos = src.find(sub, pos + 1)

answered May 16, 2020 at 17:05

mascai's user avatar

mascaimascai

1,1551 gold badge8 silver badges26 bronze badges

1

Whatever the solutions provided by others are completely based on the available method find() or any available methods.

What is the core basic algorithm to find all the occurrences of a
substring in a string?

def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

You can also inherit str class to new class and can use this function
below.

class newstr(str):
def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

Calling the method

newstr.find_all(‘Do you find this answer helpful? then upvote
this!’,’this’)

answered Feb 15, 2018 at 20:02

naveen raja's user avatar

This is solution of a similar question from hackerrank. I hope this could help you.

import re
a = input()
b = input()
if b not in a:
    print((-1,-1))
else:
    #create two list as
    start_indc = [m.start() for m in re.finditer('(?=' + b + ')', a)]
    for i in range(len(start_indc)):
        print((start_indc[i], start_indc[i]+len(b)-1))

Output:

aaadaa
aa
(0, 1)
(1, 2)
(4, 5)

darkByt3's user avatar

answered Jan 20, 2020 at 22:47

Ruman Khan's user avatar

if you want to use without re(regex) then:

find_all = lambda _str,_w : [ i for i in range(len(_str)) if _str.startswith(_w,i) ]

string = "test test test test"
print( find_all(string, 'test') ) # >>> [0, 5, 10, 15]

answered Nov 5, 2021 at 8:38

WangSung's user avatar

WangSungWangSung

2192 silver badges5 bronze badges

Here’s a solution that I came up with, using assignment expression (new feature since Python 3.8):

string = "test test test test"
phrase = "test"
start = -1
result = [(start := string.find(phrase, start + 1)) for _ in range(string.count(phrase))]

Output:

[0, 5, 10, 15]

answered Apr 8, 2022 at 10:06

Mike's user avatar

MikeMike

1132 silver badges6 bronze badges

I think the most clean way of solution is without libraries and yields:

def find_all_occurrences(string, sub):
    index_of_occurrences = []
    current_index = 0
    while True:
        current_index = string.find(sub, current_index)
        if current_index == -1:
            return index_of_occurrences
        else:
            index_of_occurrences.append(current_index)
            current_index += len(sub)

find_all_occurrences(string, substr)

Note: find() method returns -1 when it can’t find anything

SUTerliakov's user avatar

SUTerliakov

4,7453 gold badges14 silver badges36 bronze badges

answered Oct 13, 2022 at 20:06

ulas.kesik's user avatar

ulas.kesikulas.kesik

1181 silver badge5 bronze badges

The pythonic way would be:

mystring = 'Hello World, this should work!'
find_all = lambda c,s: [x for x in range(c.find(s), len(c)) if c[x] == s]

# s represents the search string
# c represents the character string

find_all(mystring,'o')    # will return all positions of 'o'

[4, 7, 20, 26] 
>>> 

perror's user avatar

perror

6,96316 gold badges58 silver badges85 bronze badges

answered Apr 10, 2018 at 19:40

Harvey's user avatar

2

if you only want to use numpy here is a solution

import numpy as np

S= "test test test test"
S2 = 'test'
inds = np.cumsum([len(k)+len(S2) for k in S.split(S2)[:-1]])- len(S2)
print(inds)

answered Jun 10, 2021 at 16:46

Phillip Maire's user avatar

please look at below code

#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''


def get_substring_indices(text, s):
    result = [i for i in range(len(text)) if text.startswith(s, i)]
    return result


if __name__ == '__main__':
    text = "How much wood would a wood chuck chuck if a wood chuck could chuck wood?"
    s = 'wood'
    print get_substring_indices(text, s)

answered Mar 16, 2017 at 1:14

黄哥Python培训's user avatar

黄哥Python培训黄哥Python培训

2392 silver badges5 bronze badges

1

def find_index(string, let):
    enumerated = [place  for place, letter in enumerate(string) if letter == let]
    return enumerated

for example :

find_index("hey doode find d", "d") 

returns:

[4, 7, 13, 15]

Sabito stands with Ukraine's user avatar

answered Nov 8, 2020 at 13:49

Elli's user avatar

1

Not exactly what OP asked but you could also use the split function to get a list of where all the substrings don’t occur. OP didn’t specify the end goal of the code but if your goal is to remove the substrings anyways then this could be a simple one-liner. There are probably more efficient ways to do this with larger strings; regular expressions would be preferable in that case

# Extract all non-substrings
s = "an-example-string"
s_no_dash = s.split('-')
# >>> s_no_dash
# ['an', 'example', 'string']

# Or extract and join them into a sentence
s_no_dash2 = ' '.join(s.split('-'))
# >>> s_no_dash2
# 'an example string'

Did a brief skim of other answers so apologies if this is already up there.

answered May 19, 2021 at 13:43

als0052's user avatar

als0052als0052

3883 silver badges12 bronze badges

def count_substring(string, sub_string):
    c=0
    for i in range(0,len(string)-2):
        if string[i:i+len(sub_string)] == sub_string:
            c+=1
    return c

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

answered Jun 2, 2021 at 3:24

CHANDANA SAMINENI's user avatar

2

I runned in the same problem and did this:

hw = 'Hello oh World!'
list_hw = list(hw)
o_in_hw = []

while True:
    o = hw.find('o')
    if o != -1:
        o_in_hw.append(o)
        list_hw[o] = ' '
        hw = ''.join(list_hw)
    else:
        print(o_in_hw)
        break

Im pretty new at coding so you can probably simplify it (and if planned to used continuously of course make it a function).

All and all it works as intended for what i was doing.

Edit: Please consider this is for single characters only, and it will change your variable, so you have to create a copy of the string in a new variable to save it, i didnt put it in the code cause its easy and its only to show how i made it work.

answered Jun 25, 2021 at 20:18

Lucas LP's user avatar

By slicing we find all the combinations possible and append them in a list and find the number of times it occurs using count function

s=input()
n=len(s)
l=[]
f=input()
print(s[0])
for i in range(0,n):
    for j in range(1,n+1):
        l.append(s[i:j])
if f in l:
    print(l.count(f))

barbsan's user avatar

barbsan

3,40811 gold badges21 silver badges28 bronze badges

answered Jul 30, 2019 at 11:44

BONTHA SREEVIDHYA's user avatar

2

To find all the occurence of a character in a give string and return as a dictionary
eg: hello
result :
{‘h’:1, ‘e’:1, ‘l’:2, ‘o’:1}

def count(string):
   result = {}
   if(string):
     for i in string:
       result[i] = string.count(i)
     return result
   return {}

or else you do like this

from collections import Counter

   def count(string):
      return Counter(string)

answered Apr 30, 2022 at 8:00

Aminu Aminaldo's user avatar

Часто нам нужно найти символ в строке 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() можно использовать в том числе и для поиска общего числа совпадений подстроки.

Many times while working with strings, we have problems dealing with substrings. This may include the problem of finding all positions of a particular substrings in a string. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension + startswith() This task can be performed using the two functionalities. The startswith function primarily performs the task of getting the starting indices of substring and list comprehension is used to iterate through the whole target string. 

Python3

test_str = "GeeksforGeeks is best for Geeks"

test_sub = "Geeks"

print("The original string is : " + test_str)

print("The substring to find : " + test_sub)

res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]

print("The start indices of the substrings are : " + str(res))

Output : 

The original string is : GeeksforGeeks is best for Geeks
The substring to find : Geeks
The start indices of the substrings are : [0, 8, 26]

Time Complexity: O(n*m), where n is the length of the original string and m is the length of the substring to find
Auxiliary Space: O(k), where k is the number of occurrences of the substring in the string

Method #2 : Using re.finditer() The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them. 

Python3

import re

test_str = "GeeksforGeeks is best for Geeks"

test_sub = "Geeks"

print("The original string is : " + test_str)

print("The substring to find : " + test_sub)

res = [i.start() for i in re.finditer(test_sub, test_str)]

print("The start indices of the substrings are : " + str(res))

Output : 

The original string is : GeeksforGeeks is best for Geeks
The substring to find : Geeks
The start indices of the substrings are : [0, 8, 26]

Method #3 : Using find() and replace() methods

Python3

test_str = "GeeksforGeeks is best for Geeks"

test_sub = "Geeks"

print("The original string is : " + test_str)

print("The substring to find : " + test_sub)

res=[]

while(test_str.find(test_sub)!=-1):

    res.append(test_str.find(test_sub))

    test_str=test_str.replace(test_sub,"*"*len(test_sub),1)

print("The start indices of the substrings are : " + str(res))

Output

The original string is : GeeksforGeeks is best for Geeks
The substring to find : Geeks
The start indices of the substrings are : [0, 8, 26]

Time Complexity: O(n*m), where n is the length of the original string and m is the length of the substring to find.
Auxiliary Space: O(k), where k is the number of occurrences of the substring in the string.

Method #4 : Using find()

The find() method is used to find the index of the first occurrence of the substring in the string. We start searching for the substring from the beginning of the string and continue searching until the substring is not found in the remaining part of the string. If the substring is found, we add its start index to the list of indices and update the start index to start searching for the next occurrence of the substring.

Python3

def find_substring_indices(string, substring):

    indices = []

    start_index = 0

    while True:

        index = string.find(substring, start_index)

        if index == -1:

            break

        else:

            indices.append(index)

            start_index = index + 1

    return indices

string = "GeeksforGeeks is best for Geeks"

substring = "Geeks"

indices = find_substring_indices(string, substring)

print("The original string is:", string)

print("The substring to find:", substring)

print("The start indices of the substrings are:", indices)

Output

The original string is: GeeksforGeeks is best for Geeks
The substring to find: Geeks
The start indices of the substrings are: [0, 8, 26]

Time complexity: O(nm) 
Auxiliary space: O(1)

Method #5: Using string slicing and while loop

  1. Initialize an empty list to store the indices of all occurrences of the substring.
  2. Set the starting index i to 0.
  3. Use a while loop to keep searching for the substring in the string.
  4. Inside the while loop, use the find() method to find the first occurrence of the substring in the string, starting from the current index i.
  5. If find() returns -1, it means that there are no more occurrences of the substring in the string, so break out of the loop.
  6. If find() returns a non-negative value, append the index of the first character of the substring to the list, and update the starting index i to the next character after the end of the substring.
  7. Repeat steps 4-6 until there are no more occurrences of the substring in the string.
  8. Return the list of indices.

Python3

def find_all_substrings(string, substring):

    indices = []

    i = 0

    while i < len(string):

        j = string.find(substring, i)

        if j == -1:

            break

        indices.append(j)

        i = j + len(substring)

    return indices

test_str = "GeeksforGeeks is best for Geeks"

test_sub = "Geeks"

print(find_all_substrings(test_str, test_sub)) 

Time complexity: O(nm), where n is the length of the string and m is the length of the substring. 
Auxiliary space: O(k), where k is the number of occurrences of the substring in the string.

Method #6 : Using re.finditer() and reduce(): 

Algorithm:

1. Import the required modules – re and functools.
2.Initialize the input string test_str and the substring to be searched test_sub.
3.Use re.finditer() to find all the occurrences of the substring test_sub in the string test_str.
4. Use reduce() to get the start indices of all the occurrences found in step 3.
5. The lambda function inside the reduce() takes two arguments – the first one is the list x that accumulates the start 6.indices and the second one is the Match object y returned by finditer(). The function adds the start index of the 7.current Match object to the list x.
8. Convert the final result to a string and print it.

Python3

import re

from functools import reduce

test_str = "GeeksforGeeks is best for Geeks"

test_sub = "Geeks"

occurrences = re.finditer(test_sub, test_str)

res = reduce(lambda x, y: x + [y.start()], occurrences, [])

print("The start indices of the substrings are : " + str(res))

Output

The start indices of the substrings are : [0, 8, 26]

Time Complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(m), where m is the number of occurrences of the substring in the input string. This is because we need to store the start indices of all the occurrences in a list.

Last Updated :
03 May, 2023

Like Article

Save Article

Базовые операции¶

# Конкатенация (сложение)
>>> s1 = 'spam'
>>> s2 = 'eggs'
>>> print(s1 + s2)
'spameggs'

# Дублирование строки
>>> print('spam' * 3)
spamspamspam

# Длина строки
>>> len('spam')
4

# Доступ по индексу
>>> S = 'spam'
>>> S[0]
's'
>>> S[2]
'a'
>>> S[-2]
'a'

# Срез
>>> s = 'spameggs'
>>> s[3:5]
'me'
>>> s[2:-2]
'ameg'
>>> s[:6]
'spameg'
>>> s[1:]
'pameggs'
>>> s[:]
'spameggs'

# Шаг, извлечения среза
>>> s[::-1]
'sggemaps'
>>> s[3:5:-1]
''
>>> s[2::2]
'aeg'

Другие функции и методы строк¶

# Литералы строк
S = 'str'; S = "str"; S = '''str'''; S = """str"""
# Экранированные последовательности
S = "snptanbbb"
# Неформатированные строки (подавляют экранирование)
S = r"C:tempnew"
# Строка байтов
S = b"byte"
# Конкатенация (сложение строк)
S1 + S2
# Повторение строки
S1 * 3
# Обращение по индексу
S[i]
# Извлечение среза
S[i:j:step]
# Длина строки
len(S)
# Поиск подстроки в строке. Возвращает номер первого вхождения или -1
S.find(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер последнего вхождения или -1
S.rfind(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер первого вхождения или вызывает ValueError
S.index(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер последнего вхождения или вызывает ValueError
S.rindex(str, [start],[end])
# Замена шаблона
S.replace(шаблон, замена)
# Разбиение строки по разделителю
S.split(символ)
# Состоит ли строка из цифр
S.isdigit()
# Состоит ли строка из букв
S.isalpha()
# Состоит ли строка из цифр или букв
S.isalnum()
# Состоит ли строка из символов в нижнем регистре
S.islower()
# Состоит ли строка из символов в верхнем регистре
S.isupper()
# Состоит ли строка из неотображаемых символов (пробел, символ перевода страницы ('f'), "новая строка" ('n'), "перевод каретки" ('r'), "горизонтальная табуляция" ('t') и "вертикальная табуляция" ('v'))
S.isspace()
# Начинаются ли слова в строке с заглавной буквы
S.istitle()
# Преобразование строки к верхнему регистру
S.upper()
# Преобразование строки к нижнему регистру
S.lower()
# Начинается ли строка S с шаблона str
S.startswith(str)
# Заканчивается ли строка S шаблоном str
S.endswith(str)
# Сборка строки из списка с разделителем S
S.join(список)
# Символ в его код ASCII
ord(символ)
# Код ASCII в символ
chr(число)
# Переводит первый символ строки в верхний регистр, а все остальные в нижний
S.capitalize()
# Возвращает отцентрованную строку, по краям которой стоит символ fill (пробел по умолчанию)
S.center(width, [fill])
# Возвращает количество непересекающихся вхождений подстроки в диапазоне [начало, конец] (0 и длина строки по умолчанию)
S.count(str, [start],[end])
# Возвращает копию строки, в которой все символы табуляции заменяются одним или несколькими пробелами, в зависимости от текущего столбца. Если TabSize не указан, размер табуляции полагается равным 8 пробелам
S.expandtabs([tabsize])
# Удаление пробельных символов в начале строки
S.lstrip([chars])
# Удаление пробельных символов в конце строки
S.rstrip([chars])
# Удаление пробельных символов в начале и в конце строки
S.strip([chars])
# Возвращает кортеж, содержащий часть перед первым шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий саму строку, а затем две пустых строки
S.partition(шаблон)
# Возвращает кортеж, содержащий часть перед последним шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий две пустых строки, а затем саму строку
S.rpartition(sep)
# Переводит символы нижнего регистра в верхний, а верхнего – в нижний
S.swapcase()
# Первую букву каждого слова переводит в верхний регистр, а все остальные в нижний
S.title()
# Делает длину строки не меньшей width, по необходимости заполняя первые символы нулями
S.zfill(width)
# Делает длину строки не меньшей width, по необходимости заполняя последние символы символом fillchar
S.ljust(width, fillchar=" ")
# Делает длину строки не меньшей width, по необходимости заполняя первые символы символом fillchar
S.rjust(width, fillchar=" ")

Форматирование строк¶

S.format(*args, **kwargs)

Примеры¶

Python: Определение позиции подстроки (функции str.find и str.rfind)¶

Определение позиции подстроки в строке с помощью функций str.find и str.rfind.

In [1]: str = 'ftp://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

Функция str.find показывает первое вхождение подстроки. Все позиции возвращаются относительно начало строки.

In [2]: str.find('/')
Out[2]: 4

In [3]: str[4]
Out[3]: '/'

Можно определить вхождение в срезе. первое число показывает начало среза, в котором производится поиск. Второе число — конец среза. В случае отсутствия вхождения подстроки выводится -1.

In [4]: str.find('/', 8, 18)
Out[4]: -1

In [5]: str[8:18]
Out[5]: '.dropbox.c'

In [6]: str.find('/', 8, 22)
Out[6]: 20

In [7]: str[8:22]
Out[7]: '.dropbox.com/u'

In [8]: str[20]
Out[8]: '/'

Функция str.rfind осуществляет поиск с конца строки, но возвращает позицию подстроки относительно начала строки.

In [9]: str.rfind('/')
Out[9]: 40

In [10]: str[40]
Out[10]: '/'

Python: Извлекаем имя файла из URL¶

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

Способ №1¶

Достаточно простой способ. Разбиваем строку по слэшам с помощью функции split(), которая возвращает список. А затем из этого списка извлекаем последний элемент. Он и будет названием файла.

In [1]: str = 'http://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

In [2]: str.split('/')
Out[2]: ['http:', '', 'dl.dropbox.com', 'u', '7334460', 'Magick_py', 'py_magick.pdf']

Повторим шаг с присвоением переменной:

In [3]: file_name = str.split('/')[-1]

In [4]: file_name
Out[4]: 'py_magick.pdf'

Способ №2¶

Второй способ интереснее. Сначала с помощью функции rfind() находим первое вхождение с конца искомой подстроки. Функция возвращает позицию подстроки относительно начала строки. А далее просто делаем срез.

In [5]: str = 'http://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

In [6]: str.rfind('/')
Out[6]: 41

Делаем срез:

In [7]: file_name = str[42:]

In [8]: file_name
Out[8]: 'py_magick.pdf'

Я начал вести список наиболее часто используемых функций, решая алгоритмические задачи на LeetCode и HackerRank.

Быть хорошим программистом — это не значит помнить все встроенные функции некоего языка. Но это не означает и того, что их запоминание — бесполезное дело. Особенно — если речь идёт о подготовке к собеседованию.

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

1. Как проверить два объекта на идентичность?

Оператор is возвращает True в том случае, если в две переменные записана ссылка на одну и ту же область памяти. Именно об этом идёт речь при разговоре об «идентичности объектов».

Не стоит путать is и ==. Оператор == проверяет лишь равенство объектов.

animals           = ['python','gopher']
more_animals      = animals
print(animals == more_animals) #=> True
print(animals is more_animals) #=> True
even_more_animals = ['python','gopher']
print(animals == even_more_animals) #=> True
print(animals is even_more_animals) #=> False

Обратите внимание на то, что animals и even_more_animals не идентичны, хотя и равны друг другу.

Кроме того, существует функция id(), которая возвращает идентификатор адреса памяти, связанного с именем переменной. При вызове этой функции для двух идентичных объектов будет выдан один и тот же идентификатор.

name = 'object'
id(name)
#=> 4408718312

2. Как проверить то, что каждое слово в строке начинается с заглавной буквы?

Существует строковый метод istitle(), который проверяет, начинается ли каждое слово в строке с заглавной буквы.

print( 'The Hilton'.istitle() ) #=> True
print( 'The dog'.istitle() ) #=> False
print( 'sticky rice'.istitle() ) #=> False

3. Как проверить строку на вхождение в неё другой строки?

Существует оператор in, который вернёт True в том случае, если строка содержит искомую подстроку.

print( 'plane' in 'The worlds fastest plane' ) #=> True
print( 'car' in 'The worlds fastest plane' ) #=> False

4. Как найти индекс первого вхождения подстроки в строку?

Есть два метода, возвращающих индекс первого вхождения подстроки в строку. Это — find() и index(). У каждого из них есть определённые особенности.

Метод find() возвращает -1 в том случае, если искомая подстрока в строке не найдена.

'The worlds fastest plane'.find('plane') #=> 19
'The worlds fastest plane'.find('car') #=> -1

Метод index() в подобной ситуации выбрасывает ошибку ValueError.

'The worlds fastest plane'.index('plane') #=> 19
'The worlds fastest plane'.index('car') #=> ValueError: substring not found

5. Как подсчитать количество символов в строке?

Функция len() возвращает длину строки.

len('The first president of the organization..') #=> 41

6. Как подсчитать то, сколько раз определённый символ встречается в строке?

Ответить на этот вопрос нам поможет метод count(), который возвращает количество вхождений в строку заданного символа.

'The first president of the organization..'.count('o') #=> 3

7. Как сделать первый символ строки заглавной буквой?

Для того чтобы это сделать, можно воспользоваться методом capitalize().

'florida dolphins'.capitalize() #=> 'Florida dolphins'

8. Что такое f-строки и как ими пользоваться?

В Python 3.6 появилась новая возможность — так называемые «f-строки». Их применение чрезвычайно упрощает интерполяцию строк. Использование f-строк напоминает применение метода format().

При объявлении f-строк перед открывающей кавычкой пишется буква f.

name = 'Chris'
food = 'creme brulee'
f'Hello. My name is {name} and I like {food}.'
#=> 'Hello. My name is Chris and I like creme brulee'

9. Как найти подстроку в заданной части строки?

Метод index() можно вызывать, передавая ему необязательные аргументы, представляющие индекс начального и конечного фрагмента строки, в пределах которых и нужно осуществлять поиск подстроки.

'the happiest person in the whole wide world.'.index('the',10,44)
#=> 23

Обратите внимание на то, что вышеприведённая конструкция возвращает 23, а не 0, как было бы, не ограничь мы поиск.

'the happiest person in the whole wide world.'.index('the')
#=> 0

10. Как вставить содержимое переменной в строку, воспользовавшись методом format()?

Метод format() позволяет добиваться результатов, сходных с теми, которые можно получить, применяя f-строки. Правда, я полагаю, что использовать format() не так удобно, так как все переменные приходится указывать в качестве аргументов format().

difficulty = 'easy'
thing = 'exam'
'That {} was {}!'.format(thing, difficulty)
#=> 'That exam was easy!'

11. Как узнать о том, что в строке содержатся только цифры?

Существует метод isnumeric(), который возвращает True в том случае, если все символы, входящие в строку, являются цифрами.

'80000'.isnumeric() #=> True

Используя этот метод, учитывайте то, что знаки препинания он цифрами не считает.

'1.0'.isnumeric() #=> False

12. Как разделить строку по заданному символу?

Здесь нам поможет метод split(), который разбивает строку по заданному символу или по нескольким символам.

'This is great'.split(' ')
#=> ['This', 'is', 'great']
'not--so--great'.split('--')
#=> ['not', 'so', 'great']

13. Как проверить строку на то, что она составлена только из строчных букв?

Метод islower() возвращает True только в том случае, если строка составлена исключительно из строчных букв.

'all lower case'.islower() #=> True
'not aLL lowercase'.islower() # False

14. Как проверить то, что строка начинается со строчной буквы?

Сделать это можно, вызвав вышеописанный метод islower() для первого символа строки.

'aPPLE'[0].islower() #=> True

15. Можно ли в Python прибавить целое число к строке?

В некоторых языках это возможно, но Python при попытке выполнения подобной операции будет выдана ошибка TypeError.

'Ten' + 10 #=> TypeError

16. Как «перевернуть» строку?

Для того чтобы «перевернуть» строку, её можно разбить, представив в виде списка символов, «перевернуть» список, и, объединив его элементы, сформировать новую строку.

''.join(reversed("hello world"))
#=> 'dlrow olleh'

17. Как объединить список строк в одну строку, элементы которой разделены дефисами?

Метод join() умеет объединять элементы списков в строки, разделяя отдельные строки с использованием заданного символа.

'-'.join(['a','b','c'])
#=> 'a-b-c'

18. Как узнать о том, что все символы строки входят в ASCII?

Метод isascii() возвращает True в том случае, если все символы, имеющиеся в строке, входят в ASCII.

print( 'Â'.isascii() ) #=> False
print( 'A'.isascii() ) #=> True

19. Как привести всю строку к верхнему или нижнему регистру?

Для решения этих задач можно воспользоваться методами upper() и lower(), которые, соответственно, приводят все символы строк к верхнему и нижнему регистрам.

sentence = 'The Cat in the Hat'
sentence.upper() #=> 'THE CAT IN THE HAT'
sentence.lower() #=> 'the cat in the hat'

20. Как преобразовать первый и последний символы строки к верхнему регистру?

Тут, как и в одном из предыдущих примеров, мы будем обращаться к символам строки по индексам. Строки в Python иммутабельны, поэтому мы будем заниматься сборкой новой строки на основе существующей.

animal = 'fish'
animal[0].upper() + animal[1:-1] + animal[-1].upper()
#=> 'FisH'

21. Как проверить строку на то, что она составлена только из прописных букв?

Имеется метод isupper(), который похож на уже рассмотренный islower(). Но isupper() возвращает True только в том случае, если вся строка состоит из прописных букв.

'Toronto'.isupper() #=> False
'TORONTO'.isupper() #= True

22. В какой ситуации вы воспользовались бы методом splitlines()?

Метод splitlines() разделяет строки по символам разрыва строки.

sentence = "It was a stormy nightnThe house creekednThe wind blew."
sentence.splitlines()
#=> ['It was a stormy night', 'The house creeked', 'The wind blew.']

23. Как получить срез строки?

Для получения среза строки используется синтаксическая конструкция следующего вида:

string[start_index:end_index:step]

Здесь step — это шаг, с которым будут возвращаться символы строки из диапазона start_index:end_index. Значение step, равное 3, указывает на то, что возвращён будет каждый третий символ.

string = 'I like to eat apples'
string[:6] #=> 'I like'
string[7:13] #=> 'to eat'
string[0:-1:2] #=> 'Ilk oetape' (каждый 2-й символ)

24. Как преобразовать целое число в строку?

Для преобразования числа в строку можно воспользоваться конструктором str().

str(5) #=> '5'

25. Как узнать о том, что строка содержит только алфавитные символы?

Метод isalpha() возвращает True в том случае, если все символы в строке являются буквами.

'One1'.isalpha() #=> False
'One'.isalpha() #=> True

26. Как в заданной строке заменить на что-либо все вхождения некоей подстроки?

Если обойтись без экспорта модуля, позволяющего работать с регулярными выражениями, то для решения этой задачи можно воспользоваться методом replace().

sentence = 'Sally sells sea shells by the sea shore'
sentence.replace('sea', 'mountain')
#=> 'Sally sells mountain shells by the mountain shore'

27. Как вернуть символ строки с минимальным ASCII-кодом?

Если взглянуть на ASCII-коды элементов, то окажется, например, что прописные буквы имеют меньшие коды, чем строчные. Функция min() возвращает символ строки, имеющий наименьший код.

min('strings') #=> 'g'

28. Как проверить строку на то, что в ней содержатся только алфавитно-цифровые символы?

В состав алфавитно-цифровых символов входят буквы и цифры. Для ответа на этот вопрос можно воспользоваться методом isalnum().

'Ten10'.isalnum() #=> True
'Ten10.'.isalnum() #=> False

29. Как удалить пробелы из начала строки (из её левой части), из её конца (из правой части), или с обеих сторон строки?

Здесь нам пригодятся, соответственно, методы lstrip(), rstrip() и strip().

string = '  string of whitespace    '
string.lstrip() #=> 'string of whitespace    '
string.rstrip() #=> '  string of whitespace'
string.strip() #=> 'string of whitespace'

30. Как проверить то, что строка начинается с заданной последовательности символов, или заканчивается заданной последовательностью символов?

Для ответа на этот вопрос можно прибегнуть, соответственно, к методам startswith() и endswith().

city = 'New York'
city.startswith('New') #=> True
city.endswith('N') #=> False

31. Как закодировать строку в ASCII?

Метод encode() позволяет кодировать строки с использованием заданной кодировки. По умолчанию используется кодировка utf-8. Если некий символ не может быть представлен с использованием заданной кодировки, будет выдана ошибка UnicodeEncodeError.

'Fresh Tuna'.encode('ascii')
#=> b'Fresh Tuna'
'Fresh Tuna Â'.encode('ascii')
#=> UnicodeEncodeError: 'ascii' codec can't encode character 'xc2' in position 11: ordinal not in range(128)

32. Как узнать о том, что строка включает в себя только пробелы?

Есть метод isspace(), который возвращает True только в том случае, если строка состоит исключительно из пробелов.

''.isspace() #=> False
' '.isspace() #=> True
'   '.isspace() #=> True
' the '.isspace() #=> False

33. Что случится, если умножить некую строку на 3?

Будет создана новая строка, представляющая собой исходную строку, повторённую три раза.

'dog' * 3
# 'dogdogdog'

34. Как привести к верхнему регистру первый символ каждого слова в строке?

Существует метод title(), приводящий к верхнему регистру первую букву каждого слова в строке.

'once upon a time'.title() #=> 'Once Upon A Time'

35. Как объединить две строки?

Для объединения строк можно воспользоваться оператором +.

'string one' + ' ' + 'string two' 
#=> 'string one string two'

36. Как пользоваться методом partition()?

Метод partition() разбивает строку по заданной подстроке. После этого результат возвращается в виде кортежа. При этом подстрока, по которой осуществлялась разбивка, тоже входит в кортеж.

sentence = "If you want to be a ninja"
print(sentence.partition(' want '))
#=> ('If you', ' want ', 'to be a ninja')

37. Строки в Python иммутабельны. Что это значит?

То, что строки иммутабельны, говорит о том, что после того, как создан объект строки, он не может быть изменён. При «модификации» строк исходные строки не меняются. Вместо этого в памяти создаются совершенно новые объекты. Доказать это можно, воспользовавшись функцией id().

proverb = 'Rise each day before the sun'
print( id(proverb) )
#=> 4441962336
proverb_two = 'Rise each day before the sun' + ' if its a weekday'
print( id(proverb_two) )
#=> 4442287440

При конкатенации 'Rise each day before the sun' и ' if its a weekday' в памяти создаётся новый объект, имеющий новый идентификатор. Если бы исходный объект менялся бы, тогда у объектов был бы один и тот же идентификатор.

38. Если объявить одну и ту же строку дважды (записав её в 2 разные переменные) — сколько объектов будет создано в памяти? 1 или 2?

В качестве примера подобной работы со строками можно привести такой фрагмент кода:

animal = 'dog'
pet = 'dog'

При таком подходе в памяти создаётся лишь один объект. Когда я столкнулся с этим в первый раз, мне это не показалось интуитивно понятным. Но этот механизм помогает Python экономить память при работе с длинными строками.

Доказать это можно, прибегнув к функции id().

animal = 'dog'
print( id(animal) )
#=> 4441985688
pet = 'dog'
print( id(pet) )
#=> 4441985688

39. Как пользоваться методами maketrans() и translate()?

Метод maketrans() позволяет описать отображение одних символов на другие, возвращая таблицу преобразования.

Метод translate() позволяет применить заданную таблицу для преобразования строки.

# создаём отображение
mapping = str.maketrans("abcs", "123S")
# преобразуем строку
"abc are the first three letters".translate(mapping)
#=> '123 1re the firSt three letterS'

Обратите внимание на то, что в строке произведена замена символов a, b, c и s, соответственно, на символы 1, 2, 3 и S.

40. Как убрать из строки гласные буквы?

Один из ответов на этот вопрос заключается в том, что символы строки перебирают, пользуясь механизмом List Comprehension. Символы проверяют, сравнивая с кортежем, содержащим гласные буквы. Если символ не входит в кортеж — он присоединяется к новой строке.

string = 'Hello 1 World 2'
vowels = ('a','e','i','o','u')
''.join([c for c in string if c not in vowels])
#=> 'Hll 1 Wrld 2'

41. В каких ситуациях пользуются методом rfind()?

Метод rfind() похож на метод find(), но он, в отличие от find(), просматривает строку не слева направо, а справа налево, возвращая индекс первого найденного вхождения искомой подстроки.

story = 'The price is right said Bob. The price is right.'
story.rfind('is')
#=> 39

Итоги

Я часто объясняю одному продакт-менеджеру, человеку в возрасте, что разработчики — это не словари, хранящие описания методов объектов. Но чем больше методов помнит разработчик — тем меньше ему придётся гуглить, и тем быстрее и приятнее ему будет работаться. Надеюсь, теперь вы без труда ответите на рассмотренные здесь вопросы.

Уважаемые читатели! Что, касающееся обработки строк в Python, вы посоветовали бы изучить тем, кто готовится к собеседованию?

Понравилась статья? Поделить с друзьями:
  • Как найти герцога рыброна в террарии
  • Как найти на работу продавца консультанта
  • Как найти людей с одинаковой фамилией
  • Как найти постоянные издержки все формулы
  • Как же далеко найти ее желаю