如果字符串以指定的前綴(字符串)開(kāi)頭,則startswith()方法將返回True。如果不是,則返回False。
startswith()的語(yǔ)法為:
str.startswith(prefix[, start[, end]])
startswith()方法最多使用三個(gè)參數(shù):
prefix -要檢查的字符串或字符串元組
start(可選)- 要在字符串中檢查前綴的開(kāi)始位置。
end (可選)- 要在字符串中檢查前綴的結(jié)束位置。
startswith()方法返回一個(gè)布爾值。
如果字符串以指定的前綴開(kāi)頭,則返回True。
如果字符串不是以指定的前綴開(kāi)頭,則返回False。
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)運(yùn)行該程序時(shí),輸出為:
False True True
text = "Python programming is easy."
#起始參數(shù): 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)運(yùn)行該程序時(shí),輸出為:
True False True
在Python中可以將前綴的元組傳遞給startswith()方法。
如果字符串以元組的任何項(xiàng)目開(kāi)頭,則startswith()返回True。如果不是,則返回False
text = "programming is easy"
result = text.startswith(('python', 'programming'))
# 輸出 True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# 輸出 False
print(result)
# 帶start 和 end 參數(shù)
# 'is easy'字符串被檢查
result = text.startswith(('programming', 'easy'), 12, 19)
# 輸出 False
print(result)運(yùn)行該程序時(shí),輸出為:
True False False
如果需要檢查字符串是否以指定的后綴結(jié)尾,則可以在Python中使用endswith()方法。