关于python:6个Python字符串判断操作方法对的用法

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

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

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())  # 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

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理