您的位置 首页 php

「Python」字符串常用操作方法 – 6个判断方法用法

所谓判断即是判断真假,返回的结果是布尔数据类型: 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  

文章来源:智云一二三科技

文章标题:「Python」字符串常用操作方法 – 6个判断方法用法

文章地址:https://www.zhihuclub.com/77040.shtml

关于作者: 智云科技

热门文章

网站地图