簡體   English   中英

如何使用 Python 查找 substring 的索引位置

[英]How to find index positions of a substring using Python

Python 在這里非常新,並且正在苦苦掙扎。 任何幫助表示贊賞:懺悔,這顯然是一個家庭作業幫助請求,但我的課程明天結束,導師需要很長時間才能回復消息。 所以我擔心如果我等待我將無法及時完成。

我正在使用康奈爾大學的一個名為 introcs 的學習模塊。 它記錄在這里: http://cs1110.cs.cornell.edu/docs/index.html

我正在嘗試編寫一個 function ,它返回一個字符串中 substring 的所有索引的元組。 我覺得我很接近,但只是不太明白。 這是我的代碼:


import introcs 

def findall(text,sub):
    result = ()
    x = 0
    pos = introcs.find_str(text,sub,x)

    for i in range(len(text)):
        if introcs.find_str(text,sub,x) != -1:
            result = result + (introcs.find_str(text,sub,x), )
            x = x + 1 + introcs.find_str(text,sub,x)

    return result

在調用findall('how now brown cow', 'ow')時,我希望它返回 (1, 5, 10, 15) 但它會刪除最后一個結果並返回 (1, 5, 10) 。

任何指針將不勝感激!

您可以使用 re 來做到這一點:

import re

found = [i.start() for i in re.finditer(substring, string)]

您不需要遍歷文本中的所有字符。 只需繼續調用introcs.find_str()直到它找不到 substring 並返回-1

您對x的新值的計算是錯誤的。 它應該比上一個匹配的索引多 1。

使result成為列表而不是元組,以便您可以使用append()添加到它。 如果你真的需要返回一個元組,你可以在最后使用return tuple(result)來轉換它。

def findall(text,sub):
    result = []
    x = 0
    while True:
        pos = introcs.find_str(text,sub,x)
        if pos == -1:
            break
        result.append(pos)
        x = pos + 1

    return result

您的代碼顯示了三個單獨嘗試跟蹤您在字符串中的位置的證據:

  1. 你用i循環它
  2. 你把 position 一個sub放在pos
  3. 你計算一個x

這里的問題是你想在這種情況下發生什么:

findall('abababa', 'aba')

您期望結果是[0, 4]還是[0, 2, 4] 假設find_str就像標准的str.find()一樣工作並且您想要[0, 2, 4]結果,您可以在先前找到的 position 之后的 1 position 處開始下一次搜索,然后從字符串的開頭開始搜索. 此外,與其將元組添加在一起,不如構建一個列表:

# this replaces your import, since we don't have access to it
class introcs:
    @staticmethod
    def find_str(text, sub, x):
        # assuming find_str is the same as str.find()
        return text.find(sub, x)


def findall(text,sub):
    result = []
    pos = -1

    while True:
        pos = introcs.find_str(text, sub, pos + 1)
        if pos == -1:
            break
        result.append(pos)

    return result


print(findall('abababa', 'aba'))

Output:

[0, 2, 4]

如果您只想匹配每個字符一次,則可以改為:

def findall(text,sub):
    result = []
    pos = -len(sub)

    while True:
        pos = introcs.find_str(text, sub, pos + len(sub))
        if pos == -1:
            break
        result.append(pos)

    return result

Output:

[0, 4]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM