Python:【字符串】 判断字符串是否以指定前缀开头(后缀结尾)


startswith() 和 endswith():

1.描述:

startswith() 方法用于判断字符串是否以指定前缀开头
endswith() 方法用于判断字符串是否以指定后缀结尾

2.语法:

S.startswith(prefix[,start=0[,end=len(S)]])
S.startswith(suffix[,start=0[,end=len(S)]])

3.参数:

  • S:父字符串
  • prefix(suffix):判定字符串
  • start:判定字符串在父字符串的起始位置,默认为0。(可选参数,默认为0)
  • end:判定字符串在父字符串的中止位置,默认为父字符串长度。(可选参数,不可单独指定)

4.返回值:

如果字符串以指定的前缀开头(后缀结尾)则返回 True,否则返回 False。

5.举例:

#python3
S="Zhangguohao love Chengnuo!!!!"
print(S.startswith("Zhang"))
print(S.startswith("love",12))
print(S.startswith("Zhang",3,7))
print(S.endswith("nuo"))

结果:

True
True
False
True