當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python String endswith()用法及代碼示例

在本教程中,我們將借助示例了解 Python String endswith() 方法。

如果字符串以指定的後綴結尾,endswith() 方法將返回 True。如果不是,則返回 False

示例

message = 'Python is fun'

# check if the message ends with fun
print(message.endswith('fun'))

# Output: True

用法:

用法:

str.endswith(suffix[, start[, end]])

參數:

endswith() 采用三個參數:

  • suffix- 要檢查的後綴字符串或元組
  • start(可選) - 起始位置後綴將在字符串中進行檢查。
  • end(可選) - 結束位置後綴將在字符串中進行檢查。

返回:

endswith() 方法返回一個布爾值。

  • 如果字符串以指定的後綴結尾,則返回 True
  • 如果字符串不以指定的後綴結尾,則返回 False

示例 1:endswith() 沒有 start 和 end 參數

text = "Python is easy to learn."

result = text.endswith('to learn')
# returns False
print(result)

result = text.endswith('to learn.')
# returns True
print(result)

result = text.endswith('Python is easy to learn.')
# returns True
print(result)

輸出

False
True
True

示例 2:endswith() 帶有 start 和 end 參數

text = "Python programming is easy to learn."

# start parameter: 7
# "programming is easy to learn." string is searched
result = text.endswith('learn.', 7)
print(result)

# Both start and end is provided
# start: 7, end: 26
# "programming is easy" string is searched

result = text.endswith('is', 7, 26)
# Returns False
print(result)

result = text.endswith('easy', 7, 26)
# returns True
print(result)

輸出

True
False
True

將元組傳遞給endswith()

可以將元組後綴傳遞給 Python 中的 endswith() 方法。

如果字符串以元組的任何項目結尾,則 endswith() 返回 True 。如果不是,則返回False

示例 3:endswith() 帶元組後綴

text = "programming is easy"
result = text.endswith(('programming', 'python'))

# prints False
print(result)

result = text.endswith(('python', 'easy', 'java'))

#prints True
print(result)

# With start and end parameter
# 'programming is' string is checked
result = text.endswith(('is', 'an'), 0, 14)

# prints True
print(result)

輸出

False
True
True

如果需要檢查字符串是否以指定前綴開頭,可以使用 startswith() method in Python

相關用法


注:本文由純淨天空篩選整理自 Python String endswith()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。