Python教程-Python字符串endswith()

位置:首页>文章>详情   分类: 教程分享 > Python教程   阅读(2037)   2023-03-28 11:29:14
Python string.endswith()用于检查特定文本模式(例如域名扩展等)的字符串结尾
Python教程

1.字符串endswith()方法

检查字符串结尾的一种简单方法是使用String.endswith()
example1.py
>>> url = 'http://www.leftso.com'
 
>>> url.endswith('.com')
 
True        #输出
 
>>> url.endswith('.net')
 
false       #输出

2.带元组的字符串endswith()

如果您需要检查多个选择,只需提供一组元串即可endswith()
example2.py
>>> domains = ["example.io", "example.com", "example.net", "example.org"]
 
>>> [name for name in domains if name.endswith(('.com', '.org')) ]
 
['example.com', 'example.org']      #输出
 
>>> any( name.endswith('.net') for name in domains )
 
True                            #输出

3.字符串endswith()与列表或集合

要使用endswith(),实际上需要元组作为输入。如果您碰巧在列表或集合中指定了选项,请确保首先使用它们进行转换tuple()
例如:
$title(example3.py)
>>> choices = ['.com', '.io', '.net']
 
>>> url = 'http://www.leftso.com'
 
>>> url.endswith(choices)      #ERROR !! TypeError: endswith first arg must be str, unicode, or tuple, not list
 
>>> url.endswith( tuple(choices) ) #Correct
 
True                            #输出


 
标签: Python教程
地址:https://www.leftso.com/article/730.html

相关阅读

前言本教程学习在Python中使用CSV文件
一.前言俗话说,工欲善其事必先利其器,本教程主要讲解如何在sublime编辑器中安装python软件包,以实现自动完成等功能,并在sublime编辑器本身中运行build
Python简介​Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布
前言在Python(或任何其他编程语言)中,注释用于解释源代码
Python –数据类型数据类型定义变量的类型
了解python中的变量,声明局部变量和全局变量
Python httplib2 简介学习使用Python httplib2模块
​Python关键字是python编程语言的保留字,这些关键字不能用于其他目的
Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头
Python示例,用于查找2个或更多词典之间的公共项,即字典相交项