在 Python 中查詢字串中的第一次出現
-
在 Python 中使用
find()函式查詢第一次出現 -
在 Python 中使用
index()函式查詢第一次出現 -
在 Python 中使用
rfind()和rindex()函式查詢最後一次出現
本教程將討論在 Python 中查詢字串中第一次出現的子字串的方法。
在 Python 中使用 find() 函式查詢第一次出現
我們可以使用 Python 中的 find() 函式來查詢字串中第一次出現的子字串。find() 函式將子字串作為輸入引數,並返回子字串在主字串中的第一個起始索引。
如果主字串中不存在子字串,則此函式返回 -1。
string = "This guy is a crazy guy."
print(string.find("guy"))
輸出:
5
我們在 "This guy is a crazy guy" 字串中找到了字串 "guy" 的第一次出現。在本例中,find() 函式返回 5 作為起始索引。
請注意,此函式還將空格計為一個字元。
在 Python 中使用 index() 函式查詢第一次出現
使用 index() 函式類似於前面討論的 find() 函式,因為它將子字串作為輸入引數並返回子字串在主字串的起始索引內的第一次出現。
string = "This guy is a crazy guy."
print(string.index("guy"))
輸出:
5
與 find() 函式一樣,index() 函式也返回 5 作為字串 "guy" 在 "This guy is a crazy guy" 字串中第一次出現的起始索引。
在 Python 中使用 rfind() 和 rindex() 函式查詢最後一次出現
前面討論的兩個函式從左到右定位主字串中的子字串。如果我們想從右到左定位子字串,也稱為子字串的最後一次出現,我們可以使用 rfind() 和 rindex() 函式。
這些函式類似於前面示例中討論的對應函式,不同之處在於它們是從右到左檢視的。以下程式碼片段顯示了這兩個函式在 Python 中的使用。
rfind():
string = "This guy is a crazy guy."
print(string.rfind("guy"))
輸出:
20
rindex():
string = "This guy is a crazy guy."
print(string.rindex("guy"))
輸出:
20
我們使用 Python 中的 rfind() 和 rindex() 函式在字串 "This guy is a crazy guy" 中找到了字串 "guy" 最後一次出現的起始索引。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn