如果字符串以給定前綴開頭,則startswith()方法返回True,否則返回False。
用法:
str.startswith(prefix, start, end)
參數:
prefix : prefix ix nothing but a string which needs to be checked. start : Starting position where prefix is needs to be checked within the string. end : Ending position where prefix is needs to be checked within the string.
注意:如果未提供開始索引和結束索引,則默認情況下它將0和length-1用作開始索引和結束索引,而我們的搜索中不包含結束索引。
返回值:
It returns True if strings starts with the given prefix otherwise returns False.
例子:
Input : text = "geeks for geeks." result = text.startswith('for geeks') Output : False Input : text = "geeks for geeks." result = text.startswith('geeks', 0) Output : True
錯誤:ValueError:在目標字符串中未找到參數字符串的情況下,會引發此錯誤
# Python code shows the working of
# .startsswith() function
text = "geeks for geeks."
# returns False
result = text.startswith('for geeks')
print (result)
# returns True
result = text.startswith('geeks')
print (result)
# returns False
result = text.startswith('for geeks.')
print (result)
# returns True
result = text.startswith('geeks for geeks.')
print (result)
輸出:
False True False True
相關用法
- Python startswith() and endswith()用法及代碼示例
- Python Pandas Series.str.startswith()用法及代碼示例
- Python string max()用法及代碼示例
- Python string min()用法及代碼示例
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python | String startswith()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。