Python之字符串判断

Python之字符串判断

首尾判断

  • endswith(suffix[, start[, end]]) -> bool
    • 在指定的区间[start, end),字符串是否是suffix结尾
  • startswith(prefix[, start[, end]]) -> bool
    • 在指定的区间[start, end),字符串是否是prefix开头
python 复制代码
a = '1,2,3,a,b,c'
# 定义一个变量
python 复制代码
a
# 返回结果:'1,2,3,a,b,c'
python 复制代码
a.startswith('1')
# 1是不是在a变量的开头,返回True False
# 返回结果:True
python 复制代码
a.endswith('c')
# c是不是在a变量的结尾,返回True False
# 返回结果:True
python 复制代码
f = 'abcdabc'
python 复制代码
f
# 返回结果:'abcdabc'
python 复制代码
f.startswith('abc', 4)
# 可以设置开始,开始位置指定4,4是索引4, 一般只指定开始,结束不作指定,因为前包后不包
# 返回结果:True

其它函数

  • upper()大写
  • lower()小写
  • swapcase() 交换大小写
  • isalnum() -> bool 是否是字母和数字组成 isalpha() 是否是字母
  • isdecimal() 是否只包含十进制数字
  • isdigit() 是否全部数字(0~9)
  • isidentifier() 是不是字母和下划线开头,其他都是字母、数字、下划线 islower() 是否都是小写
  • isupper() 是否全部大写
  • isspace() 是否只包含空白字符
python 复制代码
f.upper() 
# 转换成大写返回全新的字符串
# 返回结果:'ABCDABC'
python 复制代码
f.lower()
# 转换成小写返回全新的字符串
# 返回结果:'abcdabc'
python 复制代码
'Abc'.istitle()
# 查询这是不是一个标题
# 返回结果:True
python 复制代码
" ".isspace()
# 返回结果:True
python 复制代码
" \t\r\n\f".isspace()
# 查询是不是空白字符
# 返回结果:True
相关推荐
阿尔的代码屋4 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django