Python startswith()和endswith()方法的用法

发布时间:2020-07-29 14:24:40 作者:小猪
来源:亿速云 阅读:157

这篇文章主要讲解了Python startswith()和endswith()方法的用法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

startswith()方法

Python startswith() 方法用于检查字符串是否是以指定子字符串开头

如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

str.startswith(str, beg=0,end=len(string));

参数

返回值

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

常用环境:用于IF判断

#!/usr/local/bin/python
# coding=utf-8
listsql = 'select * from ifrs.indiv_info'
def isSelect(sql):
  chsql = sql.upper().strip()
  if not chsql.startswith("SELECT "):
    return False
  return True

print isSelect(listsql)
[root@bigdata-poc-shtz-3 zw]# python h.py
True

endswith()方法

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

一、函数说明

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

string[beg:end].endswith(str)

参数说明:

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

返回值:

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

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

注:会认为空字符为真

python
>>> endsql = 'select * from ifrs.indiv_info'
>>> endsql.endswith('info')
True
>>> endsql.endswith('info',3)
True
>>>
>>> endsql.endswith('info',3,10)
False
>>> endsql.endswith('info',25,29)
True
>>> endsql.endswith('')
True

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

>>> f = 'a.txt'
>>> if f.endswith(('.txt')):
... print '%s is a txt' %f
... else:
... print '%s is not a txt' %f
...
a.txt is a txt

看完上述内容,是不是对Python startswith()和endswith()方法的用法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. ubunt18.04LTS+vscode+anaconda3下的python+C++调试方法
  2. 使用C++调用Python代码的方法详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python startswith endswith

上一篇:Android PC端用ADB抓取指定应用日志的实现方法

下一篇:关于Python数据分析的小技巧

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》