Python教程-Python字符串endswith()

教程分享 > Python教程 (5230) 2024-07-19 16:50:13

Python string.endswith()用于检查特定文本模式(例如域名扩展等)的字符串结尾

 

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                            #输出



 

https://www.leftso.com/article/730.html

相关文章
前言本教程学习在Python中使用CSV文件
Python简介​Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布
一.前言俗话说,工欲善其事必先利其器,本教程主要讲解如何在sublime编辑器中安装python软件包,以实现自动完成等功能,并在sublime编辑器本身中运行build
前言在Python(或任何其他编程语言)中,注释用于解释源代码
Python –数据类型数据类型定义变量的类型
了解python中的变量,声明局部变量和全局变量
Python httplib2 简介学习使用Python httplib2模块
​Python关键字是python编程语言的保留字,这些关键字不能用于其他目的
Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头
Python示例,用于查找2个或更多词典之间的公共项,即字典相交项
Python string.endswith()用于检查特定文本模式(例如域名扩展等)的字符串结尾
使用字符串中的分隔符将字符串拆分为字段的 Python示例
1. Python整数类型值​​​​​​​​在Python中,一个int或整数是:不含小数的整数正,负或零无限长度可能包含下划线以提高可读性x = 10 y = 123456789876543...
Python示例将N元素元组或序列解压缩为N个变量的集合
​​​​​​​​Python 语言中的String在Python中,String代指以下特点:代表Unicode字符的字节数组用单引号或双引号引起来无限长度Python 中 String 字符串...