
所谓判断即是判断真假,返回的结果是布尔数据类型: True 或 False
以下是字符串常用操作方法中的6个判断方法,每个方法都有语法且利用案例来说明怎么使用,方法使用很简单,大家快速掌握就好。虽说字符串的一些操作方法很简单,可能会有刚接触编程的小白不是特别理解,我们有配套的python视频教程,不大懂得宝宝可以去看看视频或许就明白了。
1、startswith()
检查字符串是否是以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。
语法:
快速体验:
myStr = 'hello world and Python and java and php'
print(myStr.startswith('hello')) # True
print(myStr.startswith('hel')) # True
print(myStr.startswith('helt')) # False
复制代码
2、endswith()
检查字符串是否是以指定子串结尾,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。
语法:
字符串序列.endswith(子串,开始位置下标,结束位置下标)
快速体验:
myStr = 'hello world and Python and java and php'
print(myStr.endswith('php')) # True
print(myStr.endswith('hp')) # True
print(myStr.endswith('ppp')) # False
print(myStr.endswith('ph')) # False
复制代码
3、isalpha()
如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。
语法:
字符串序列.isalpha()
快速体验:
myStr1 = 'python'
myStr2 = 'python123456'
print(myStr1.isalpha()) # True
print(myStr2.isalpha()) # False
复制代码
4、isdigit()
如果字符串只包含数字则返回True,否则返回False。
语法: *
字符串序列.isdigit()
快 速体验:
myStr1 = 'python123'
myStr2 = '123456'
print(myStr1.isdigit()) # False
print(myStr2.isdigit()) # True
复制代码
5、isalnum()
如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。
语法:
字符串序列.isdigit()
快速体验:
myStr1 = 'python123'
myStr2 = '123456--、、'
print(myStr1.isalnum()) # True
print(myStr2.isalnum()) # False
复制代码
6、isspace()
如果字符串中只包含空白,则返回True,否则返回False。
语法:
字符串序列.isspace()
快速体验:
myStr1 = 'p y t h o n 1 2 3'
myStr2 = ' '
print(myStr1.isspace()) # False
print(myStr2.isspace()) # True
海报
179
相关文章
- Python 3.12 新特性解析:模式匹配增强与性能优化实战
- Lightly IDE 深度评测:轻量级 Python 开发工具是否适合团队协作?
- VS Code 自定义配置:JSON 文件修改、代码片段与任务自动化脚本
- Python 虚拟环境选择:venv、conda、poetry 的适用场景对比
- PyCharm+GitHub Copilot:Python 开发中 AI 辅助编码的最佳实践
- PyCharm 无法识别虚拟环境?5 步排查 Python 解释器配置问题
- 数据科学工具链:Jupyter Notebook+RStudio+Python 的协同工作流
- Python 3.12 新特性:模式匹配增强与性能改进实战
- Lightly IDE 适合谁?轻量级 Python 开发工具深度评测
- Python IDE 终极对比:PyCharm vs VS Code vs Jupyter Notebook