Python字符串的判断操作(starswith、endswith等)

返回值是布尔类型:True或者False。

startswith()检查字符串是否以指定的子串开头。
endswith()检查字符串是否以指定的子串结尾。

1、startswith() 检查指定字符串是否以指定的子串开头。

1)语法

字符串序列.startswith(子串[, 开始位置下标, 结束位置下标])

检查指定字符串是否以指定的子串开头,是则返回True,否则返回False。若设置了开始和 结束位置下标,则在指定返回查找。

2)实例

mystr = 'hello,python,hello,java and hello php'

print(mystr.startswith('python'))   #False
print(mystr.startswith('hel'))    #True
print(mystr.startswith('python',6,16))  #True

2、endswith() 检查字符串是否以指定的子串结尾。

1)语法

字符串序列.endswith(子串[, 开始位置下标, 结束位置下标])

检查指定字符串是否以指定的子串结尾,是则返回True,否则返回False。

2)实例

mystr = 'hello,python,hello,java and hello php'

print(mystr.endswith('php'))    # True
print(mystr.endswith('python')) #False
print(mystr.endswith('ph'))     #False
print(mystr.endswith('hp'))     #True
print(mystr.endswith('lo',10,18))   #True

其他判断字符串的方法:

isidentifier()判断指定的字符串是不是合法的标识符
isspace()判断指定的字符串是否全部由空白字符组成(空格、回车换行、制表符等)
isalpha()判断指定的字符串是否全部由字母组成
isdecimal()判断指定的字符串是否全部由十进制的数字组成
isnumeric()判断指定的字符串是否全部由数字组成
isdigit()判断指定的字符串是否只由数字组成,只对 0 和 正数有效。
isalnum()判断指定字符串是否全部由字母和数字组成

代码演示:

#合法标识符
s1 = 'hello'
s2 = 'python%'
print(s1.isidentifier())    #True
print(s2.isidentifier())    #False
print('张三_'.isidentifier())    #True  Python中允许使用汉字作为标识符,但要尽量避免

#空白符
print('\t'.isspace())   #True
print(''.isspace())   #False

#字母
print('abc'.isalpha())  #True
print('as3d'.isalpha()) #False

#数字
print('23878'.isdecimal())    #True
print('2314A'.isdecimal())      #False

print('345'.isnumeric())    #True
print('345三'.isnumeric())    #True
print('345a'.isnumeric())    #False

#字母和数字
print('123as'.isalnum())    #True
print('876三'.isalnum())     #True
print('23878'.isalnum())    #True

isnumeric() 和 isdigit() 的区别:

isnumeric() :可以判断中文数字,罗马数字、全角数字(双字节)、Unicode数字(双字节)。

isdigit() :可以判断单字节数字、全角数字(双字节)、Unicode数字(双字节),不能判断汉字数字和罗马数字。

print('5678'.isnumeric())   #True
print('5678'.isdigit())     #True

print('一二三'.isnumeric())    #True
print('一二三'.isdigit())      #False

print('Ⅳ'.isnumeric())      #True
print('Ⅳ'.isdigit())    #False
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容