老生常谈Python startswith()函数与endswith函数

作者:jingxian 时间:2023-06-03 02:02:42 

函数:startswith()

作用:判断字符串是否以指定字符或子字符串开头

一、函数说明

语法:string.startswith(str, beg=0,end=len(string))
      或string[beg:end].startswith(str)

参数说明:

string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)

如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查

返回值

如果检测到字符串,则返回True,否则返回False。默认空字符为True

函数解析:如果字符串string是以str开始,则返回True,否则返回False

二、实例


>>> s = 'hello good boy doiido'
>>> print s.startswith('h')
True
>>> print s.startswith('hel')
True
>>> print s.startswith('h',4)
False
>>> print s.startswith('go',6,8)
True

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

用环境:用于if判断


>>> if s.startswith('hel'):
print "you are right"
else:
print "you are wrang"
you are right

函数:endswith()

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

一、函数说明

语法: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

来源:http://www.cnblogs.com/qianyuliang/p/7491100.html

标签:python,startswith,endswith
0
投稿

猜你喜欢

  • 利用python实现平稳时间序列的建模方式

    2022-08-31 03:35:30
  • Python经典案例之图像漫水填充分割详解

    2021-08-25 11:41:14
  • Linux下python制作名片示例

    2022-06-07 00:29:33
  • 查询mysql中执行效率低的sql语句的方法

    2024-01-24 09:58:36
  • Python实现列表中非负数保留,负数转化为指定的数值方式

    2022-07-23 21:23:24
  • Python hashlib模块加密过程解析

    2021-09-08 13:29:25
  • 深入讲解SQL中的字符串拼接

    2024-01-23 17:52:00
  • python读写数据读写csv文件(pandas用法)

    2021-06-15 15:28:03
  • 详解设计模式中的工厂方法模式在Python程序中的运用

    2022-11-14 01:06:58
  • Python callable内置函数原理解析

    2022-02-16 11:27:03
  • 高质量Python代码编写的5个优化技巧

    2022-04-20 16:49:16
  • Java 正则表达式功能及应用

    2022-03-25 10:07:09
  • python获取本机外网ip的方法

    2022-06-24 01:57:16
  • Python数据分析之使用scikit-learn构建模型

    2023-11-10 23:19:10
  • Python实现合成多张图片到PDF格式

    2023-02-26 04:57:25
  • Pycharm无法显示动态图片的解决方法

    2023-01-29 23:13:42
  • Python时间模块datetime、time、calendar的使用方法

    2023-04-02 06:44:16
  • python读写配置文件操作示例

    2021-12-12 03:51:29
  • gulp-htmlmin压缩html的gulp插件实例代码

    2023-08-06 01:20:18
  • MySql常用命令总结

    2009-09-16 10:51:00
  • asp之家 网络编程 m.aspxhome.com