欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python endswith()函數(shù)的具體使用

 更新時間:2023年07月14日 09:21:29   作者:士別三日wyx  
本文主要介紹了Python endswith()函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

endwith() 可以「判斷」字符串是否以指定內(nèi)容「結(jié)尾」。

語法

string.endwith( str, start, end )

參數(shù)

  • str :(必選,字符串或元組)指定字符串或元素
  • start :(可選)開始的索引,默認(rèn)值0
  • end :(可選)結(jié)束的索引,默認(rèn)值-1

返回值

  • 以指定內(nèi)容結(jié)尾返回 True
  • 不以指定內(nèi)容結(jié)尾返回 False

實例:判斷字符串是否以 ‘world’ 結(jié)尾

print('hello world'.endswith('world'))

輸出:

True

1、指定范圍

設(shè)置開始和結(jié)束的「索引」來指定范圍,索引從0開始。

只設(shè)置「開始」的索引,默認(rèn)檢查到字符串末尾,即[start,末尾]

print('hello world'.endswith('world', 1))

輸出:

True

同時設(shè)置「開始」、「結(jié)束」的索引,可以檢測字符串的某個范圍內(nèi)是否以指定內(nèi)容結(jié)尾。

print('hello world'.endswith('world', 0, 5))

輸出:

False

從輸出結(jié)果可以發(fā)現(xiàn),字符串(0~5)索引是‘hello ’,不以‘world’結(jié)尾,所以返回False。

除了在 endwith() 參數(shù)中設(shè)置索引,還可以通過字符串的索引來指定范圍

print('hello world'[0:5].endswith('world'))

輸出:

False

2、str可以傳入元組

str 參數(shù)只能是字符串或者元祖(元素都是字符串類型),否則會報錯 TypeError: endswith first arg must be str or a tuple of str

傳入元素都是字符串的類型的「元祖」,會自動遍歷并判斷字符串是否以元組中的元素結(jié)尾,只要滿足一個,就返回True;全部不滿足,就返回False。

print('hello world'.endswith(('world', 'a')))
print('hello world'.endswith(('b', 'a')))

輸出:

True
False

實例:文件后綴名黑名單

file_name = 'shell.php'
if file_name.endswith(('php', 'jsp', 'asp')):
    print('被禁止的文件類型,請重新上傳')
else:
    print('上傳成功')

如果只有「列表」,可以轉(zhuǎn)成數(shù)組再判斷

list1 = ['world', 'a', 'b']
tuple1 = tuple(list1)
print('hello world'.endswith(tuple1))

輸出:

True

3、空字符串為真

判斷字符串是否以 空字符串""結(jié)尾時,會返回True。

print('hello world'.endswith(''))
print('*&ab31'.endswith(''))

輸出:

True
True

「空格」就不行了,會返回False

print('hello world'.endswith(' '))

輸出:

False

4、大小寫敏感

endwith() 判斷時,區(qū)分「大小寫」,這導(dǎo)致我們匹配不到一些文件后綴名,比如下面這樣會返回False

file_name = 'shell.PHP'
print(file_name.endswith('php'))

輸出:

False

我們可以先 lower() 轉(zhuǎn)成小寫,再進(jìn)行判斷

file_name = 'shell.pHp'
print(file_name.lower().endswith('php'))

輸出:

True

到此這篇關(guān)于Python endswith()函數(shù)的具體使用的文章就介紹到這了,更多相關(guān)Python endswith()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論