所谓判断即是判断真假,返回的结果是布尔数据类型: True 或 False
以下是字符串常用操作方法中的6个判断方法,每个方法都有语法且利用案例来说明怎么使用,方法使用很简单,大家快速掌握就好。虽说字符串的一些操作方法很简单,可能会有刚接触编程的小白不是特别理解,我们有配套的python视频教程,不大懂得宝宝可以去看看视频或许就明白了。
1、startswith()
检查字符串是否是以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。
语法:
字符串序列.startswith(子串,开始位置下标,结束位置下标)
快速体验:
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()) # Trueprint(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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/73371.html