Python 的 str.startswith(~) 方法返回 boolean 指示字符串是否以指定的 prefix 開頭。
參數
1. prefix | string
要在源字符串中檢查的前綴。
2. start | int | optional
要開始搜索的源字符串的索引(包含)。默認情況下,start=0 。
3. end | int | optional
要停止搜索的源字符串的索引(不包括)。默認情況下,end= start + len(prefix) 。
返回值
單個 boolean 指示源字符串是否以指定的 prefix 開頭。
例子
基本用法
要檢查源字符串 'abc def' 是否以前綴 'ab' 開頭:
x = 'abc def'
x.startswith('ab')
True
啟動參數
要檢查源字符串 'abc def' 是否以前綴 'ab' 開頭,從索引位置 1 開始:
y = 'abc def'
y.startswith('ab', 1)
False
搜索從索引位置 1 開始,該位置位於 'b' 。由於 'bc' 與提供的 'ab' 前綴不匹配,因此返回 False。
結束參數
要檢查源字符串 'abc def' 是否以前綴 'abc' 開頭,從索引位置 0 (包含)開始並在索引位置 2 (不包含)結束:
z = "abc def"
z.startswith("abc", 0, 2)
False
搜索的起始位置是索引位置 0 ( 'a' ),搜索在索引位置 2 ( 'c' ) 之前結束。因此,我們檢查字符串 'ab' 是否以前綴 'abc' 開頭,返回 False 。
相關用法
- Python String startswith()用法及代碼示例
- Python String strip方法用法及代碼示例
- Python String strip()用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String split方法用法及代碼示例
- Python String splitlines方法用法及代碼示例
- Python String split()用法及代碼示例
- Python String swapcase()用法及代碼示例
- Python String swapcase方法用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | startswith method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
