Tutorial Study Image

Python endswith()

Python 中的 endswith() 函数用于检查字符串是否以给定的后缀结尾。如果是,函数返回 true,否则返回 false。


str.endswith(suffix[, start[, end]]) #where index is an integer value
 

endswith() 参数

endswith() 函数接受三个参数。如果未指定起始和结束前缀,则默认情况下它将检查从零索引开始的整个字符串。

参数 描述 必需/可选
后缀 (suffix) 要检查的后缀字符串或后缀元组 必需
开始 (start) 在字符串中检查后缀的起始位置 可选
结束 (end) 在字符串中检查后缀的结束位置 可选

endswith() 返回值

返回值始终是布尔值。也可以向此方法传递元组后缀。如果字符串以元组中的任何元素结尾,则此函数返回 true。

输入 返回值
如果字符串以指定的后缀结尾 True
如果字符串不以指定的后缀结尾 False

Python 中 endswith() 方法的示例

示例 1:endswith() 在没有 start 和 end 参数的情况下如何工作?


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

示例 2:endswith() 在有 start 和 end 参数的情况下如何工作?


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

示例 3: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