Python 字符串endswith()
原文:https://www.studytonight.com/python-library-functions/python-string-endswith
Python 字符串endswith()
是一个内置函数,如果字符串以特定的后缀结束,则返回true
;否则它将返回false
。
在这种情况下,如果没有指定开始和结束索引,那么默认情况下开始被视为
0
长度被视为-1
结束索引不包括在我们的搜索中。如果字符串是以
endswith()
函数中使用的为后缀的,则函数将返回true
,否则将返回false
。如果您想检查字符串是否以列表中的一个字符串结尾,那么在这种情况下,使用字符串
endswith()
函数。此方法返回布尔值。
这个函数也接受元组;我们将通过例子向你展示
Python 字符串endswith()
:语法
下面我们有一个 Python 中字符串endswith()
的基本语法:
string.endswith(suffix, start, end)
Python 字符串endswith()
:参数
endswith()
参数描述如下:
- 字尾
此参数用于指定字符串的一部分,我们将检查字符串是否以该部分结尾。
- 启动
这是一个可选参数,从这里开始后缀。
- 结束
它是一个可选参数,后缀将在此结束。
Python 字符串endswith()
:返回值
对于返回值,有两种情况:
如果字符串以指定的后缀结束,则返回真。
如果字符串没有以指定的后缀结束,则返回假。
Python 字符串endswith()
:基本示例
下面我们有一个例子来展示 String endswith()
函数的工作原理:
string = "Hello I am Ram and I am a developer"
result = string.endswith("per")
result1 = string.endswith("PER")
print("Comparing it with right suffix so output: ",result)
print("Comparing it with wrong suffix so output: ",result1)
其输出如下所示:
将其与正确的后缀进行比较,输出:真 将其与错误的后缀进行比较,输出:假
Python 字符串endswith()
:使用开始和结束参数
在下面给出的例子中,我们将同时使用endswith()
的开始和结束参数。让我们看看代码片段:
abc = "This is a string and is awesome"
right_suffix = "some"
wrong_suffix = "some!"
print(abc.endswith(right_suffix, 28, 31))
print(abc.endswith(wrong_suffix, 28, 31))
其输出如下所示:
假 假
Python String endswith()
: 元组后缀
在这个例子中,我们正在检查字符串是否以元组中的一个字符串结束。让我们看看代码片段:
text = "StudyTonight"
result = text.endswith(('Study', 'Otis'))
print(result)
result = text.endswith(('Study', 'night'))
print(result)
其输出如下所示:
假 真
Python 字符串endswith()
:使用列表
在本例中,我们正在检查字符串是否以列表中的某个字符串结尾。让我们看看代码片段:
ext = ['.jpg','.png']
file = 'test.png'
print(file.endswith(('.jpg', '.png')))
其输出如下所示:
真
时间就是活生生的例子!
现在让我们看一个活生生的例子,以便完全理解endswith()
方法:
摘要
在本教程中,我们学习了endswith()
方法及其参数和返回值的描述。我们还使用了元组和列表作为后缀。还有一个endswith()
方法的活例子。