1. 程式人生 > 其它 >python字串-結尾判斷(endswith)

python字串-結尾判斷(endswith)

endswith方法判斷字串是否以指定字尾結尾。

語法

S.endswith(suffix[, start[, end]]) -> bool

引數

  • suffix: 指定的字尾字串,也可以是一個元組。
  • start: 可選引數,字串的開始位置。
  • end: 可選引數,字串的結束位置。

返回值

  • 包含指定字尾返回True,否則返回False。

示例

str = '我愛我的爸媽'
print(str.endswith('媽'))
print(str.endswith('爸媽'))
print(str.endswith('爸'))
print(str.endswith('爸', 0, len(str)-1))
# 可以使用元組作為引數,只要元組中包含結尾的字串就返回True
print(str.endswith(('爸', '媽')))
True
True
False
True
True

help()

Help on built-in function endswith:

endswith(...) method of builtins.str instance
    S.endswith(suffix[, start[, end]]) -> bool
    
    Return True if S ends with the specified suffix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.