在Python中查找子字符串索引的5種方法

在Python中查找字符串中子字符串索引的5種方法 (5 Ways to Find the Index of a Substring in Strings in Python)

  1. str.find()

    str.find()

  2. str.rfind()

    str.rfind()

  3. str.index()

    str.index()

  4. str.rindex()

    str.rindex()

  5. re.search()

    re.search()

str.find() (str.find())

str.find() returns the lowest index in the string where the substring sub is found within the slice s[start:end]. It returns -1 if the sub is not found.start and end are optional arguments.

str.find()返回在切片s[start:end]找到子字符串sub的字符串中的最低索引。 如果找不到該子項,則返回-1startend是可選參數。

str.find(sub,start,end)

例子1.使用str.find()方法 (Example 1. Using str.find() method)

Image for post
Photo by the author
作者照片

The string is banana.

線是banana

The substring is an.

該子是an

The substring occurs two times in the string.

子字符串在字符串中出現兩次。

str.find(“an”) returns the lowest index of the substring an.

str.find(“an”)返回子字符串an的最低索引。

s1="banana"print (s1.find("an"))#Output:1

例子2.使用str.find()方法和提到的start參數 (Example 2. Using str.find() method with the start parameter mentioned)

The substring is an.

該子是an

The start parameter is 2. It will start searching the substring an from index 2.

起始參數為2 。 它將開始從索引2搜索子字符串an

s1="banana"print (s1.find("an",2))#Output:3

例子3.如果沒有找到子字符串,它將返回-1 (Example 3. If the substring is not found, it will return -1)

The substring is ba.

子字符串是ba

The start parameter is 1 and the stop parameter is 5. It will start searching the substring from index 1 to index 5 (excluded).

起始參數為1 ,終止參數為5 。 它將開始搜索從索引1到索引5(不包括)的子字符串。

Since the substring is not found in the string within the given index, it returns -1.

由于在給定索引的字符串中找不到子字符串,因此它返回-1

s1="banana"print (s1.find("ba",1,5))#Output:-1

2. str.rfind() (2. str.rfind())

str.rfind() returns the highest index in the string where the substring sub is found within the slice s[start:end]. It returns -1 if the sub is not found.start and end are optional arguments.

str.rfind()返回在slice s[start:end]找到子字符串sub的字符串中的最高索引。 如果找不到該子項,則返回-1startend是可選參數。

str.rfind(sub,start,end)

例子1.使用str.rfind()方法 (Example 1. Using str.rfind() method)

Image for post
Photo by the author
作者照片

The string is banana.

線是banana

The substring is an.

該子是an

The substring occurs two times in the string.

子字符串在字符串中出現兩次。

str.find(“an”) returns the highest index of the substring an.

str.find(“an”)返回子字符串an的最高索引。

s1="banana"print (s1.rfind("an"))#Output:3

例子2.使用str.rfind()方法并提到開始和結束參數 (Example 2. Using str.rfind() method with the start and end parameters mentioned)

The substring is an.

該子是an

The start and end parameters are 1 and 4, respectively. It will start searching the substring from index 1 and index 4 (excluded).

startend參數分別為14 。 它將開始從索引1和索引4(排除)中搜索子字符串。

s1="banana"print (s1.rfind("an",1,4))#Output:1

例子3.如果沒有找到子字符串,它將返回-1 (Example 3. If the substring is not found, it will return -1)

The substring is no.

子字符串為no

Since the substring is not found in the string, it returns -1.

由于在字符串中找不到子字符串,因此它返回-1

s1="banana"print (s1.rfind("no"))#Output:-1

3. str.index() (3. str.index())

Similarly to find(), str.index() returns the lowest index of the substring found in the string. It raises a ValueError when the substring is not found.

find()類似, str.index()返回 字符串中找到的子字符串的最低索引。 當找不到子字符串時,它將引發ValueError

例子1.使用str.index()方法 (Example 1. Using str.index() method)

s1="banana"print (s1.index("an"))#Output:1

例子2.在給定start和end參數的情況下使用str.index()方法 (Example 2. Using str.index() method with the start and end parameters given)

s1="banana"print (s1.index("an",2,6))#Output:3

例子3.如果沒有找到子字符串,它將引發一個ValueError (Example 3. If the substring is not found, it raises a ValueError)

s1="banana"print (s1.index("no"))#Output:ValueError: substring not found

4. str.rindex() (4. str.rindex())

Similarly to find(), str.rindex() returns the highest index of the substring found in the string. It raises a ValueError when the substring is not found.

find()類似, str.rindex()返回在字符串中找到的子字符串的最高索引。 當找不到子字符串時,它將引發ValueError

例子1.使用str.rindex()方法 (Example 1. Using str.rindex() method)

s1="banana"print (s1.rindex("an"))#Output:3

例子2.在給定start和end參數的情況下使用str.index()方法 (Example 2. Using str.index() method with the start and end parameters given)

s1="banana"print (s1.rindex("an",0,4))#Output:1

例子3.如果沒有找到子字符串,它將引發一個ValueError (Example 3. If the substring is not found, it raises a ValueError)

s1="banana"print (s1.rindex("no"))#Output:ValueError: substring not found

5. re.search() (5. re.search())

re.search(pattern, string, flags=0)

“Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.” — Python’s official documentation

“掃描字符串以查找正則表達式模式產生匹配項的第一個位置,然后返回相應的匹配對象。 如果字符串中沒有位置與模式匹配,則返回None否則,返回None 。 請注意,這不同于在字符串中的某個位置找到零長度匹配。” — Python的官方文檔

  • re.search (pattern, string): We have to mention the pattern to be searched in the string.

    re.search (模式,字符串):我們不得不提一下pattern中要搜索string

  • The return type matches the object that contains the starting and ending index of that pattern (substring).

    返回類型與包含該模式(子字符串)的開始和結束索引的對象匹配。
  • We can find the start and end indices from the match object using match.start() and match.end().

    我們可以使用match.start()match.end()從match對象中找到startend索引。

Match.start([group])Match.end([group])

“Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match.” — Python’s documentation

“返回分組匹配的子字符串的開始和結束的索引; 默認為零(表示整個匹配的子字符串)。 如果存在但沒有參與比賽,則返回-1 。” — Python的文檔

  • We can get the start and end indices in tuple format using match.span().

    我們可以使用match.span()獲得元組格式的startend索引。

Match.span([group])

“For a match m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). group defaults to zero, the entire match.” — Python’s documentation

“對于匹配項m ,返回2元組(m.start(group), m.end(group)) 。 請注意,如果group對匹配沒有貢獻,則為(-1, -1)默認為零,即整個匹配。” — Python的文檔

例子1.使用re.search() (Example 1. Using re.search())

示例2.如果在字符串中未找到子字符串,則返回None (Example 2. If a substring is not found in the string, it returns None)

import re
string = 'banana'pattern = 'no'match=(re.search(pattern, string))#Returns match objectprint (match)#Output: None

結論 (Conclusion)

  • Python 3.8.1 is used.

    使用Python 3.8.1。
  • str.find(), str.rfind() — Returns -1 when a substring is not found.

    str.find()str.rfind() —在找不到子字符串時返回-1

  • str.index(),str.rindex() — Raises a ValueError when a substring is not found.

    str.index()str.rindex() —在找不到子字符串時引發ValueError

  • re.search() — Returns None when a substring is not found.

    re.search() —如果找不到子字符串,則返回None

  • str.find(), str,index() — Returns the lowest index of the substring.

    str.find()str,index() —返回子字符串的最低索引。

  • str.rfind(), str.rindex() — Returns the highest index of the substring.

    str.rfind()str.rindex() —返回子字符串的最高索引。

  • re.search() — Returns the match object that contains the starting and ending indices of the substring.

    re.search() —返回包含子字符串的開始和結束索引的匹配對象。

資源(Python文檔) (Resources (Python Documentation))

  • str.find

    查找

  • str.index

    指數

  • str.rfind

    查找

  • str.rindex

    索引

  • re.search

    研究

  • match-objects

    匹配對象

翻譯自: https://medium.com/better-programming/5-ways-to-find-the-index-of-a-substring-in-python-13d5293fc76d

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388137.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388137.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388137.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[LeetCode] 3. Longest Substring Without Repeating Characters 題解

問題描述 輸入一個字符串,找到其中最長的不重復子串 例1: 輸入:"abcabcbb" 輸出:3 解釋:最長非重復子串為"abc" 復制代碼例2: 輸入:"bbbbb" 輸出:1 解…

WPF中MVVM模式的 Event 處理

WPF的有些UI元素有Command屬性可以直接實現綁定&#xff0c;如Button 但是很多Event的觸發如何綁定到ViewModel中的Command呢&#xff1f; 答案就是使用EventTrigger可以實現。 繼續上一篇對Slider的研究&#xff0c;在View中修改Interaction. <i:Interaction.Triggers>&…

Eclipse 插件開發 向導

閱讀目錄 最近由于特殊需要&#xff0c;開始學習插件開發。   下面就直接弄一個簡單的插件吧!   1 新建一個插件工程   2 創建自己的插件名字&#xff0c;這個名字最好特殊一點&#xff0c;一遍融合到eclipse的時候&#xff0c;不會發生沖突。   3 下一步&#xff0c;進…

線性回歸 假設_線性回歸的假設

線性回歸 假設Linear Regression is the bicycle of regression models. It’s simple yet incredibly useful. It can be used in a variety of domains. It has a nice closed formed solution, which makes model training a super-fast non-iterative process.線性回歸是回…

ES6模塊與commonJS模塊的差異

參考&#xff1a; 前端模塊化 ES6 在語言標準的層面上&#xff0c;實現了模塊功能&#xff0c;而且實現得相當簡單&#xff0c;旨在成為瀏覽器和服務器通用的模塊解決方案。 其模塊功能主要由兩個命令構成&#xff1a;export和import。export命令用于規定模塊的對外接口&#x…

solo

solo - 必應詞典 美[so?lo?]英[s??l??]n.【樂】獨奏(曲)&#xff1b;獨唱(曲)&#xff1b;單人舞&#xff1b;單獨表演adj.獨唱[奏]的&#xff1b;單獨的&#xff1b;單人的v.獨奏&#xff1b;放單飛adv.獨網絡梭羅&#xff1b;獨奏曲&#xff1b;索羅變形復數&#xff1…

Eclipse 簡介和插件開發天氣預報

Eclipse 簡介和插件開發 Eclipse 是一個很讓人著迷的開發環境&#xff0c;它提供的核心框架和可擴展的插件機制給廣大的程序員提供了無限的想象和創造空間。目前網上流傳相當豐富且全面的開發工具方面的插件&#xff0c;但是 Eclipse 已經超越了開發環境的概念&#xff0c;可以…

趣味數據故事_壞數據的好故事

趣味數據故事Meet Julia. She’s a data engineer. Julia is responsible for ensuring that your data warehouses and lakes don’t turn into data swamps, and that, generally speaking, your data pipelines are in good working order.中號 EETJulia。 她是一名數據工程…

Linux 4.1內核熱補丁成功實踐

最開始公司運維同學反饋&#xff0c;個別宿主機上存在進程CPU峰值使用率異常的現象。而數萬臺機器中只出現了幾例&#xff0c;也就是說萬分之幾的概率。監控產生的些小誤差&#xff0c;不會造成宕機等嚴重后果&#xff0c;很容易就此被忽略了。但我們考慮到這個異常轉瞬即逝、并…

python分句_Python循環中的分句,繼續和其他子句

python分句Python中的循環 (Loops in Python) for loop for循環 while loop while循環 Let’s learn how to use control statements like break, continue, and else clauses in the for loop and the while loop.讓我們學習如何在for循環和while循環中使用諸如break &#xf…

eclipse plugin 菜單

簡介&#xff1a; 菜單是各種軟件及開發平臺會提供的必備功能&#xff0c;Eclipse 也不例外&#xff0c;提供了豐富的菜單&#xff0c;包括主菜單&#xff08;Main Menu&#xff09;&#xff0c;視圖 / 編輯器菜單&#xff08;ViewPart/Editor Menu&#xff09;和上下文菜單&am…

[翻譯 EF Core in Action 2.0] 查詢數據庫

Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的關于Entityframework Core 書籍。原版地址. 是除了官方文檔外另一個學習EF Core的不錯途徑, 書中由淺入深的講解的EF Core的相關知識。因為沒有中文版,所以本人對其進行翻譯。 預計每兩天…

hdu5692 Snacks dfs序+線段樹

題目傳送門 題目大意&#xff1a;給出一顆樹&#xff0c;根節點是0&#xff0c;有兩種操作&#xff0c;一是修改某個節點的value&#xff0c;二是查詢&#xff0c;從根節點出發&#xff0c;經過 x 節點的路徑的最大值。 思路&#xff1a;用樹狀數組寫發現還是有些麻煩&#xff…

python數據建模數據集_Python中的數據集

python數據建模數據集There are useful Python packages that allow loading publicly available datasets with just a few lines of code. In this post, we will look at 5 packages that give instant access to a range of datasets. For each package, we will look at h…

打開editor的接口討論

【打開editor的接口討論】 先來看一下workbench吧&#xff0c;workbench從靜態劃分應該大致如下&#xff1a; 從結構圖我們大致就可以猜測出來&#xff0c;workbench page作為一個IWorkbenchPart&#xff08;無論是eidtor part還是view part&#…

【三角函數】已知直角三角形的斜邊長度和一個銳角角度,求另外兩條直角邊的長度...

如圖,已知直角三角形ABC中,∠C90, ∠Aa ,ABc ,求直角邊AC、BC的長度. ∵ ∠C90,∠Aa ,ABc ,Cos∠AAC/AB ,Sin∠ABC/AB ,∴ ACAB*Cos∠Ac*Cosa ,BCAB*Sin∠Ac*Sina . 復制代碼

網絡攻防技術實驗五

2018-10-23 實驗五 學 號201521450005 中國人民公安大學 Chinese people’ public security university 網絡對抗技術 實驗報告 實驗五 綜合滲透 學生姓名 陳軍 年級 2015 區隊 五 指導教師 高見 信息技術與網絡安全學院 2018年10月23日 實驗任務總綱 2018—2019 …

usgs地震記錄如何下載_用大葉草繪制USGS地震數據

usgs地震記錄如何下載One of the many services provided by the US Geological Survey (USGS) is the monitoring and tracking of seismological events worldwide. I recently stumbled upon their earthquake datasets provided at the website below.美國地質調查局(USGS)…

Springboot 項目中 xml文件讀取yml 配置文件

2019獨角獸企業重金招聘Python工程師標準>>> 在xml文件中讀取yml文件即可&#xff0c;代碼如下&#xff1a; 現在spring-boot提倡零配置&#xff0c;但是的如果要集成老的spring的項目&#xff0c;涉及到的bean的配置。 <bean id"yamlProperties" clas…

eclipse 插件打包發布

如果想把調試好的插件打包發布&#xff0c;并且在ECLIPSE中可以使用. 1.File-->Export 2.選擇 PLug-in Development下 的 Deployable plug-ins and fragments 3.進入 Deployable plug-ins and fragments 頁面 4.把底下的 Destubatuib 的選項中選擇 Archive file 在這里添入要…