Python中提供了大量的字符串處理函數(shù),可以幫助我們完成各種各樣的字符串處理工作。
Python內(nèi)置的startswith()函數(shù)可以幫助我們判斷一個字符串中是否以某一特定的前綴字符串開始,并返回邏輯值:True或False。
同時,該函數(shù)提供了可選的兩個參數(shù),分別用于指定在字符串中搜索的起始位置和停止位置。
startswith()函數(shù)的語法格式如下:
string_object.startswith(prefix,start,end)
各參數(shù)的含義如下:
下面使用一些例子舉例講解這個函數(shù)的使用方法。
test_str = "武林網(wǎng)VEVB的文章貴在專業(yè)"
rtn_result = test_str.startswith("武林網(wǎng)")
print(rtn_result)
rtn_result = test_str.startswith("IT")
print(rtn_result)
輸出:
True
False
在沒有指定第2個和第3個參數(shù)時,startswith()函數(shù)默認從開始位置開始搜索。
在Python 3.8.2中的執(zhí)行情況:
test_str = "搜索武林網(wǎng)VEVB,發(fā)現(xiàn)更多樂趣。"
rtn_result = test_str.startswith("武林網(wǎng)", 2)
print(rtn_result)
這里指定了start參數(shù),則從索引為2的位置(即“翔”字開始的位置)開始搜索。
在Python3.8.2中的執(zhí)行情況如下圖所示:
test_str = "搜索武林網(wǎng)VEVB,site:VeVb.com"
rtn_result = test_str.startswith("武林網(wǎng)", 1, 5)
print(rtn_result)
這里同時指定了start參數(shù)和end參數(shù),則從索引位置1到索引位置5進行搜索。
在Python3.8.2中的執(zhí)行情況如下圖所示:
test_str = "搜索武林網(wǎng)VEVB"
rtn_result = test_str.startswith("百度")
print(rtn_result)
在Python3.8.2中的執(zhí)行情況如下圖所示:
雖然官方文檔中沒有明確指出負數(shù)情況,但是基于Python中字符串切片處理的原則,很多字符串處理函數(shù)中可以使用負數(shù)來指定索引位置。負數(shù)即從字符串尾部往前數(shù)的位置。
test_str = "武林網(wǎng)VEVB"
rtn_result = test_str.startswith("IT", -4)
print(rtn_result)
rtn_result = test_str.startswith("IT", -3)
print(rtn_result)
rtn_result = test_str.startswith("IT", -5, -2)
print(rtn_result)
rtn_result = test_str.startswith("IT", -4, -2)
print(rtn_result)
以上例子在Python3.8.2中運行情況如下圖所示:
test_str = "武林網(wǎng)VEVB"
search_str = "it"
rtn_result = test_str.startswith(search_str, 3)
print(rtn_result)
rtn_result = test_str.startswith(search_str.upper(), 3)
print(rtn_result)
在Python3.8.2中的執(zhí)行情況如下圖所示:
這個例子中,使用到了Python中的另外一個函數(shù)upper(),該函數(shù)的作用是將字符串中的英文字母都變成大寫形式。
從這里可以看出,第一個輸出False,認為指定的開始位置不是"it"字符串,第2個輸出True,因為將待搜索字符串變?yōu)榇髮懞螅梢栽谥付ㄎ恢谜业搅恕?/p>
新聞熱點
疑難解答
圖片精選