python 中的endswith()
函數有助於檢查字元串是否以給定的後綴結尾。如果是,函數返回 true,否則返回 false。
**str.endswith(suffix[, start[, end]])** #where index is an integer value
endswith()
參數:
endswith()
函數接受三個參數。如果沒有指定開始和結束前綴,那麼默認情況下,它將從零索引開始檢查整個字元串。
參數 | 描述 | 必需/可選 |
---|---|---|
後綴 | 要檢查的後綴字元串或元組 | 需要 |
開始 | 字元串中檢查後綴的起始位置 | 可選擇的 |
目標 | 字元串中要檢查後綴的結束位置 | 可選擇的 |
endswith()
返回值
返回值始終是布爾值。也可以將元組後綴傳遞給這個方法。如果字元串以元組的任何元素結尾,則該函數返回 true。
| 投入 | 返回值 |
| 如果字元串以指定的後綴結尾 | 真實的 |
| 如果字元串不以指定的後綴結尾 | 錯誤的 |
Python 中endswith()
方法的示例
示例endswith()
在沒有開始和結束參數的情況下如何工作?
string = "Hii, How are you?"
result = string.endswith('are you')
# returns False
print(result)
result = string.endswith('are you?')
# returns True
print(result)
result = string.endswith('Hii, How are you?')
# returns True
print(result)
輸出:
False
True
True
示例endswith()
如何使用開始和結束參數?
string = "Hii, How are you?"
# start parameter: 10
result = string.endswith('you?', 10)
print(result)
# Both start and end is provided
result = string.endswith('are?', 2, 8)
# Returns False
print(result)
result = string.endswith('you?', 10, 16)
# returns True
print(result)
輸出:
True
False
True
示例endswith()
如何使用元組後綴?
string = "apple is a fruit"
result = string.endswith(('apple', 'flower'))
# prints False
print(result)
result = string.endswith(('apple', 'fruit', 'grapes'))
#prints True
print(result)
# With start and end parameter
result = string.endswith(('is', 'to'), 0, 8)
# prints True
print(result)
輸出:
True
False
True
原創文章,作者:KEU0N,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/130295.html