本文將對Python中的find方法進行詳細的介紹。首先,find方法可以用於尋找字元串中的某個特定子串。比如,我們有一個字元串:”Python is a popular programming language.” 我們可以通過find方法來尋找”programming” 這個子串是否在這個字元串中。
str = "Python is a popular programming language." pos = str.find('programming') if pos >= 0: print('The substring is found at position', pos) else: print('The substring is not found')
一、參數介紹
find方法的基本語法如下:
find(substring, start, end)
其中,substring為要查找的子串,可以是字元串也可以是單個字元;start為查找的起始位置,end為查找的終止位置。如果沒有指定start和end,則在整個字元串中查找。
如果找到了指定的子串,則返回該子串在原字元串中的開始位置。如果沒有找到,則返回-1。
二、查找某個字元是否在字元串中
可以使用find方法來判斷某個字元是否在字元串中。比如,我們要判斷字元’a’ 是否在字元串”hello world!” 中。
str = "hello world!" pos = str.find('a') if pos >= 0: print('The character is found at position', pos) else: print('The character is not found')
運行結果:
The character is not found
三、查找子串在字元串中的位置
例:查找字元串”programming” 在字元串”Python is a popular programming language.” 中的位置。
str = "Python is a popular programming language." pos = str.find('programming') if pos >= 0: print('The substring is found at position', pos) else: print('The substring is not found')
運行結果:
The substring is found at position 22
四、從指定位置開始查找子串
可以指定查找子串的起始位置。比如我們要在字元串”Python is a popular programming language.” 中查找”program”這個子串,但是我們只想在字元串的後半部分進行查找。
str = "Python is a popular programming language." pos = str.find('program', 20) if pos >= 0: print('The substring is found at position', pos) else: print('The substring is not found')
運行結果:
The substring is found at position 22
五、查找多個相同的子串
可以查找多個相同的子串,並返回其位置。比如,我們要查找字元串”programming” 在字元串”Python is a popular programming language. Programming is fun!” 中出現的所有位置。
str = "Python is a popular programming language. Programming is fun!" pos = -1 while True: pos = str.find('programming', pos+1) if pos == -1: break print('The substring is found at position', pos)
運行結果:
The substring is found at position 22 The substring is found at position 38
六、結尾
至此,我們詳細介紹了Python中的find方法,從參數介紹、查找某個字元是否在字元串中、查找子串在字元串中的位置、從指定位置開始查找子串以及查找多個相同的子串等多個方面進行了闡述。find方法是Python中很常用的字元串方法,希望本文可以幫助讀者更好的掌握。
原創文章,作者:RHAVL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/373339.html