新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonfind()
python 中的find()函數(shù)有助于返回給定子串的位置。如果它們不止一次出現(xiàn),它將返回第一次出現(xiàn)。如果沒有找到搜索到的子串,它將返回-1。

**str.find(sub[, start[, end]] )** #where start & end must be an integers
查找()參數(shù):
find()函數(shù)接受三個(gè)參數(shù)。如果缺少開始和結(jié)束參數(shù),它將把零作為開始索引,把 length-1 作為結(jié)束參數(shù)。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 潛水艇 | 必須找到其索引的子字符串 | 需要 |
| 開始 | 字符串中開始搜索的位置。默認(rèn)值為 0 | 可選擇的 |
| 目標(biāo) | 定位,直到搜索應(yīng)該發(fā)生。默認(rèn)值是字符串的結(jié)尾 | 可選擇的 |
查找()返回值
返回值始終是指定子字符串位置或索引的整數(shù)值。這個(gè)方法類似于index()方法,不同的是,如果沒有找到搜索到的子串,index()會(huì)拋出一個(gè)異常。
| 投入 | 返回值 | | 如果找到子字符串 | 給定值 | | 如果沒有找到子字符串 | -1 |
Python 中find()方法的示例
示例 1:如何在沒有開始和結(jié)束參數(shù)的情況下找到()。
string = 'What is the, what is the, what is the'
# first occurance of 'what is'(case sensitive)
result = string.find('what is')
print("Substring 'what is':", result)
# find returns -1 if substring not found
result = string.find('Hii')
print("Substring 'Hii ':", result)
# How to use find() in conditions
if (string.find('is,') != -1):
print("Contains substring 'is,'")
else:
print("Doesn't contain substring")
輸出:
Substring 'let it': 13
Substring 'small ': -1
Contains substring 'is,'
示例find()如何處理開始和結(jié)束參數(shù)?
string = 'What is your name'
# Substring is searched in 'your name'
print(string.find('your name', 7))
# Substring is searched in ' is your'
print(string.find('is your', 10))
# Substring is searched in 'what is'
print(string.find('what is', 8, 16))
# Substring is searched in 'is your'
print(string.find('is your ', 0, 14))
輸出:
8
-1
-1
5 網(wǎng)站題目:創(chuàng)新互聯(lián)Python教程:Pythonfind()
路徑分享:http://www.dlmjj.cn/article/dpgedss.html


咨詢
建站咨詢
