所谓判断即是判断虚实,返回的后果是布尔数据类型: True 或 False

以下是字符串罕用操作方法中的6个判断办法,每个办法都有语法且利用案例来阐明怎么应用,办法应用很简略,大家疾速把握就好。

1、startswith()

查看字符串是否是以指定子串结尾,是则返回True,否则返回False。如果设置开始和完结地位下标,则在指定范畴内查看。

语法:

字符串序列.startswith(子串,开始地位下标,完结地位下标)

疾速体验:

myStr = 'hello world and Python and java and php'print(myStr.startswith('hello'))  # Trueprint(myStr.startswith('hel'))    # Trueprint(myStr.startswith('helt'))   # False

2、endswith()

查看字符串是否是以指定子串结尾,是则返回True,否则返回False。如果设置开始和完结地位下标,则在指定范畴内查看。

语法:

字符串序列.endswith(子串,开始地位下标,完结地位下标)

疾速体验:

myStr = 'hello world and Python and java and php'print(myStr.endswith('php'))  # Trueprint(myStr.endswith('hp'))    # Trueprint(myStr.endswith('ppp'))   # Falseprint(myStr.endswith('ph'))   # False

3、isalpha()

如果字符串至多有一个字符并且所有字符都是字母则返回True,否则返回False。

语法:

字符串序列.isalpha()

疾速体验:

myStr1 = 'python'myStr2 = 'python123456'print(myStr1.isalpha())  # Trueprint(myStr2.isalpha())  # False

4、isdigit()

如果字符串只蕴含数字则返回True,否则返回False。

语法:

字符串序列.isdigit()

疾速体验:

myStr1 = 'python123'myStr2 = '123456'print(myStr1.isdigit())  # Falseprint(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())  # Falseprint(myStr2.isspace())  # True

文章借鉴出处:www.wakey.com.cn/video-column.html