string.endswith()方法
string.endswith()方法:
如果字符串以指定的后缀结尾,则endswith()方法返回True。 如果不是,则返回False。
语法如下:
str.endswith(suffix[, start[, end]])
endswith()参数
endwith()采用三个参数:
- suffix-要检查的后缀的字符串或元组
- start(可选参数)-在字符串中检查后缀的开始位置。
- end(可选参数)-在字符串中检查后缀的结束位置。
从endswith()返回值:
endswith()方法返回一个布尔值。
- 如果字符串以指定的后缀结尾,则返回True。
- 如果字符串不以指定的后缀结尾,则返回False。
下面,我将举例子来理解:
示例1:没有start and end参数的endswith()
text = "Python is easy to learn."
result = text.endswith('to learn')
print(result)
result = text.endswith('to learn.')
print(result)
result = text.endswith('Python is easy to learn.')
print(result)
输出:
False
True
True
示例2:带有start and end参数的endswith()
text = "Python programming is easy to learn."
result = text.endswith('learn.', 7)
print(result)
result = text.endswith('is', 7, 26)
print(result)
result = text.endswith('easy', 7, 26)
print(result)
输出:
True
False
True
将元组传递给endswith()
可以在Python中将元组后缀传递给endswith()方法。
如果字符串以元组的任何元素结尾,则endswith()返回True。 如果不是,则返回False.
我们还是举个例子来理解一下:
示例3:带有元组后缀的endswith()
text = "programming is easy"
result = text.endswith(('programming', 'python'))
print(result)
result = text.endswith(('python', 'easy', 'java'))
print(result)
result = text.endswith(('is', 'an'), 0, 14)
print(result)
输出:
False
True
True
如果需要检查字符串是否以指定的前缀开头,则可以在Python中使用startswith()方法。
后面我也会写关于在Python中使用startswith()方法这一节。