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
相关推荐
钱栈up7 分钟前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu10 分钟前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
卿卿的产品经理日记20 分钟前
【AI产品经理实战】Day 48|AI 回答变短了,到底是谁的功劳?
人工智能·笔记·aigc·产品经理
Agent世界1 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维
用户298698530142 小时前
Python 自动化处理 Word:按规则查找并高亮关键文本
python·api·编程语言
人工智能技术咨询.3 小时前
什么才算高质量数据集
python
DanCheng-studio3 小时前
毕业设计项目 机器视觉指纹识别特征对比算法(源码+论文)
python·毕业设计·毕设
梅雅达编程笔记4 小时前
一份 PDF 到底该拆成什么存进去:RAG 智能问答毕设数据库设计完整教程
python·flask·智能问答·毕设·向量数据库·rag·数据库设计
AI创界者4 小时前
Python 进阶实战(第八十三章):基于 Redis Lua 脚本的分布式令牌桶限流、异步熔断器状态机与信号优雅关机实战
人工智能·python·aigc
whyTeaFo13 小时前
GAMES202: Lecture 4: Real-Time Shadows 2 ppt笔记
笔记