Python3 笔记:字符串的 startswith() 和 endswith()

1、startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定了值,则在指定范围内检查。

语法:str.startswith(substr, beg=0,end=len(string))

参数:

str -- 检测的字符串。

substr -- 指定的子字符串。

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

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

python 复制代码
str1 = 'this is a test'
print(str1.startswith('this'))	# 运行结果:True
print(str1.startswith('this',2))	# 运行结果:False
print(str1.startswith('this',0,6))	# 运行结果:True

2、endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。

语法:str.endswith(suffix, start\[, end])

参数

suffix -- 该参数可以是一个字符串或者是一个元素。

start -- 字符串中的开始位置。

end -- 字符中结束位置。

python 复制代码
str1 = 'this is a test'
print(str1.endswith('this'))	# 运行结果:False
print(str1.endswith('test',2))	# 运行结果:True
print(str1.endswith('this',0,9))	# 运行结果:False
print(str1.endswith('this',0,4))	# 运行结果:True
相关推荐
用户83562907805143 分钟前
使用 Python 操作 Word 内容控件
后端·python
码云骑士2 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
闪闪发亮的小星星3 小时前
高斯光以及高斯光公式解释
笔记
闵孚龙3 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
goldenrolan3 小时前
A公司物料替代测试系统 v1.7:从需求到 exe/apk 的 AI 辅助全链路实践
android·自动化测试·软件测试·python·ai
菜板春3 小时前
jupyter入门-手册-特征探索
python·jupyter
Metaphor6924 小时前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
cqbzcsq4 小时前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
极光代码工作室4 小时前
基于数据仓库的电商数据分析平台
大数据·hadoop·python·spark·数据可视化