python字符串startswith_Python 字符串 startswith() 使用方法及示例
Python 字符串 startswith() 使用方法及示例
如果字符串以指定的前綴(字符串)開頭,則startswith()方法將返回True。如果不是,則返回False。
startswith()的語法為:str.startswith(prefix[,?start[,?end]])
startswith()參數
startswith()方法最多使用三個參數:prefix -要檢查的字符串或字符串元組
start(可選)- ?要在字符串中檢查前綴的開始位置。
end?(可選)- ?要在字符串中檢查前綴的結束位置。
startswith()返回值
startswith()方法返回一個布爾值。如果字符串以指定的前綴開頭,則返回True。
如果字符串不是以指定的前綴開頭,則返回False。
示例1:startswith()沒有start和end參數
示例text?=?"Python?is?easy?to?learn."
result?=?text.startswith('is?easy')
#?返回?False
print(result)
result?=?text.startswith('Python?is?')
#?返回?True
print(result)
result?=?text.startswith('Python?is?easy?to?learn.')
#?返回?True
print(result)
運行該程序時,輸出為:False
True
True
示例2:startswith()帶start和end參數
示例text?=?"Python?programming?is?easy."
#起始參數:?7
#?'programming?is?easy.'?字符串被搜索
result?=?text.startswith('programming?is',?7)
print(result)
#?start:?7,?end:?18
#?'programming'?字符串被搜索
result?=?text.startswith('programming?is',?7,?18)
print(result)
result?=?text.startswith('program',?7,?18)
print(result)
運行該程序時,輸出為:True
False
True
將元組傳遞給startswith()
在Python中可以將前綴的元組傳遞給startswith()方法。
如果字符串以元組的任何項目開頭,則startswith()返回True。如果不是,則返回False
示例3:具有元組前綴的startswith()
示例text?=?"programming?is?easy"
result?=?text.startswith(('python',?'programming'))
#?輸出?True
print(result)
result?=?text.startswith(('is',?'easy',?'java'))
#?輸出?False
print(result)
#?帶start?和?end?參數
#?'is?easy'字符串被檢查
result?=?text.startswith(('programming',?'easy'),?12,?19)
#?輸出?False
print(result)
運行該程序時,輸出為:True
False
False
如果需要檢查字符串是否以指定的后綴結尾,則可以在Python中使用endswith()方法。
總結
以上是生活随笔為你收集整理的python字符串startswith_Python 字符串 startswith() 使用方法及示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js hover图片放大不遮挡_CSS3
- 下一篇: 我有一部安卓手机忘记了手绘解锁图案,怎么