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
相关推荐
熊猫钓鱼>_>5 分钟前
ArkTS 装饰器总览:V1 / V2 / 通用装饰器完整学习笔记
笔记·学习·华为·交互·harmonyos·arkts·arkweb
SamChan906 分钟前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步201514 分钟前
Python全栈项目--智能办公自动化系统
开发语言·python
GLDbalala20 分钟前
GPU PRO 5 - 5.2 glTF: Designing an Open-Standard Runtime Asset Format笔记
笔记
春生野草28 分钟前
个人笔记——栈
笔记
颜酱43 分钟前
09 | 重构项目结构
人工智能·python·langchain
chnyi6_ya1 小时前
论文阅读笔记 | One Sentence, One Drama: 基于多智能体系统的个性化短剧生成
论文阅读·笔记
ysa0510301 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
Dory_Youth2 小时前
联想笔记本电脑失灵
运维·笔记·电脑
Sisphusssss3 小时前
香橙派5plus GPIO
linux·python·ubuntu