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

9次阅读

共计 1319 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0