Python中endswith()函数的基本使用

作者:goldensun 时间:2022-06-05 04:01:34 

函数:endswith()

作用:判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型

相关函数:判断字符串开头 startswith()


一、函数说明
语法:string.endswith(str, beg=[0,end=len(string)])
           string[beg:end].endswith(str)

参数说明:
string: 被检测的字符串
str:      指定的字符或者子字符串(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选,从左数起)
end:    设置字符串检测的结束位置(可选,从左数起)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查 
 
返回值:
如果检测到字符串,则返回True,否则返回False。

解析:如果字符串string是以str结束,则返回True,否则返回False

注:会认为空字符为真

二、实例
 


>>> s = 'hello good boy doiido'
>>> print s.endswith('o')
True
>>> print s.endswith('ido')
True
>>> print s.endswith('do',4)
True
>>> print s.endswith('do',4,15)
False




#匹配空字符集
>>> print s.endswith('')
True
#匹配元组
>>> print s.endswith(('t','b','o'))
True

 
常用环境:用于判断文件类型(比如图片,可执行文件)


>>> f = 'pic.jpg'
>>> if f.endswith(('.gif','.jpg','.png')):
 print '%s is a pic' %f
else:
 print '%s is not a pic' %f

pic.jpg is a pic
标签:Python
0
投稿

猜你喜欢

  • 基于Python3.6中的OpenCV实现图片色彩空间的转换

    2022-05-20 14:03:13
  • php控制反转与依赖注入举例讲解

    2023-06-10 10:30:22
  • python开发之文件操作用法实例

    2022-08-07 02:03:45
  • MYSQL不能从远程连接的一个解决方法(s not allowed to connect to this MySQL server)

    2024-01-19 02:57:34
  • Python 模拟动态产生字母验证码图片功能

    2022-02-10 21:03:35
  • windows下MySQL数据库移动到其它盘

    2024-01-21 01:08:32
  • python先序遍历二叉树问题

    2023-10-09 10:25:30
  • 基于javascript实现最简单的选项卡切换效果

    2023-08-25 00:26:23
  • vue货币过滤器的实现方法

    2024-05-09 10:40:58
  • 使用Python创建简单的HTTP服务器的方法步骤

    2023-07-17 01:33:27
  • 根据表名和索引获取需要的列名的存储过程

    2011-09-30 11:54:42
  • Python时间处理模块Time和DateTime

    2021-10-12 18:04:38
  • Python异常处理机制结构实例解析

    2021-11-30 15:59:27
  • MySQL中使用FREDATED引擎实现跨数据库服务器、跨实例访问

    2024-01-25 12:55:52
  • Python实现选择排序

    2021-06-17 03:23:40
  • 利用python清除移动硬盘中的临时文件

    2022-12-07 21:43:11
  • Python 转换时间戳为指定格式日期

    2023-11-05 13:48:41
  • sqlserver通用的删除服务器上的所有相同后缀的临时表

    2012-06-06 20:07:34
  • Python中让MySQL查询结果返回字典类型的方法

    2024-01-25 04:37:33
  • 微信小程序单选框自定义赋值

    2024-04-18 09:49:50
  • asp之家 网络编程 m.aspxhome.com