Python startswith()和endswith() 方法原理解析

2020-04-29,

startswith()方法

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

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

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

参数

  • str --检测的字符串。
  • strbeg --可选参数用于设置字符串检测的起始位置。
  • strend --可选参数用于设置字符串检测的结束位置。

返回值

如果检测到字符串则返回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)

参数说明:

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

如果存在参数 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() 方法原理解析.doc》

下载本文的Word格式文档,以方便收藏与打印。