簡體   English   中英

Python:在字符串中查找子串並返回子串的索引

[英]Python: Find a substring in a string and returning the index of the substring

我有:

  • 一個函數: def find_str(s, char)

  • 和一個字符串: "Happy Birthday"

我本質上想輸入"py"並返回3但我一直讓2返回。

代碼:

def find_str(s, char):
    index = 0           
    if char in s:
        char = char[0]
        for ch in s:
            if ch in s:
                index += 1
            if ch == char:
                return index

    else:
        return -1

print(find_str("Happy birthday", "py"))

不知道出了什么問題!

在字符串對象上有一個內置方法find

s = "Happy Birthday"
s2 = "py"

print(s.find(s2))

Python 是一種“包含電池的語言”,其中編寫的代碼可以完成您想要的大部分工作(無論您想要什么).. 除非這是作業:)

如果find字符串,則find返回 -1。

理想情況下,您會像瘋狂刺蝟所說的那樣使用str.findstr.index 但是你說你不能...

您的問題是您的代碼僅搜索搜索字符串的第一個字符(第一個字符)位於索引 2 處。

您基本上是說如果char[0]s ,則增加index直到ch == char[0]在我測試時返回 3 但它仍然是錯誤的。 這是一種方法。

def find_str(s, char):
    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

它產生了以下輸出:

3
8
-1

正則表達式中還有另一種選擇,即search方法

import re

string = 'Happy Birthday'
pattern = 'py'
print(re.search(pattern, string).span()) ## this prints starting and end indices
print(re.search(pattern, string).span()[0]) ## this does what you wanted

順便說一句,如果你想找到一個模式的所有出現,而不僅僅是第一個,你可以使用finditer方法

import re

string = 'i think that that that that student wrote there is not that right'
pattern = 'that'

print([match.start() for match in re.finditer(pattern, string)])

這將打印匹配的所有起始位置。

添加到 @demented 刺蝟答案中使用find()

效率方面

在調用find()之前首先檢查 s1 是否在 s2 中可能是值得的。
如果您知道大多數時候 s1 不會是 s2 的子字符串,這會更有效

由於in運算符非常有效

 s1 in s2

轉換可能更有效:

index = s2.find(s1)

index = -1
if s1 in s2:
   index = s2.find(s1)

這對於find()將大量返回 -1 時很有用。

我發現它的速度要快得多,因為在我的算法中多次調用find() ,所以我認為值得一提

聚會遲到,正在搜索相同的內容,因為“in”無效,我剛剛創建了以下內容。

def find_str(full, sub):
    index = 0
    sub_index = 0
    position = -1
    for ch_i,ch_f in enumerate(full) :
        if ch_f.lower() != sub[sub_index].lower():
            position = -1
            sub_index = 0
        if ch_f.lower() == sub[sub_index].lower():
            if sub_index == 0 :
                position = ch_i

            if (len(sub) - 1) <= sub_index :
                break
            else:
                sub_index += 1

    return position

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

產生

3
8
-1

刪除 lower() 以防不區分大小寫的 find 不需要。

這是一個簡單的方法:

my_string = 'abcdefg'
print(text.find('def'))

輸出:

3

我的子串不存在,你會得到-1 例如:

my_string = 'abcdefg'
print(text.find('xyz'))

輸出:

-1

有時,如果子字符串不存在,您可能想拋出異常:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

輸出:

回溯(最近一次調用最后一次):

文件“test.py”,第 6 行,在print(text.index('xyz'))

值錯誤:未找到子字符串

沒有直接回答這個問題,但我最近收到了一個類似的問題,我被要求計算一個子字符串在給定字符串中重復的次數。 這是我寫的函數:

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

find() 函數可能只返回第一次出現的索引。 存儲索引而不是僅僅計數,可以為我們提供子字符串在字符串中重復的不同索引集。

免責聲明:我對 Python 編程“非常”陌生。

暫無
暫無

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

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