1. 程式人生 > >python中startswith()函式的用法

python中startswith()函式的用法

python字串函式用法大全連結

startswith()函式

描述:判斷字串是否以指定字元或子字串開頭。

語法:str.endswith("suffix", start, end) 或

str[start,end].endswith("suffix")    用於判斷字串中某段字串是否以指定字元或子字串結尾。

—> bool    返回值為布林型別(True,False)

  • suffix — 字尾,可以是單個字元,也可以是字串,還可以是元組("suffix"中的引號要省略)。
  • start —索引字串的起始位置。
  • end — 索引字串的結束位置。
  • str.endswith(suffix)  star預設為0,end預設為字串的長度減一(len(str)-1)

注意:空字元的情況。返回值通常也為True

程式示例:

str = "hello,i love python"
print("1:",str.startswith("h"))
print("2:",str.startswith("l",2,10))# 索引 llo,i lo 是否以“n”結尾。
print("3:",str.startswith("")) #空字元
print("4:",str[0:6].startswith("h")) # 只索引  hello,
print("5:",str[0:6].startswith("e"))
print("6:",str[0:6].startswith(""))
print("7:",str.startswith(("h","z")))#遍歷元組的元素,存在即返回True,否者返回False
print("8:",str.startswith(("k","m")))

程式執行結果:

1: True
2: True
3: True
4: True
5: False
6: True
7: True
8: False