1、S.isalpha()
判断字符串是否全部是“字母+中文”
res = 'aa中国'.isalpha()
print(res)
运行结果:
True
那如果只想判断是不是字母呢?
res1 = 'aa中国'.encode(encoding='utf-8').isalpha()
res2 = 'aa'.isalpha()
print(res1)
print(res2)
运行结果:
False
True
2、S.isspace()
判断字符串是不是全空格
res1 = ' '.isspace()
res2 = 'None'.isspace()
res3 = ' a '.isspace()
print(res1)
print(res2)
print(res3)
运行结果:
True
False
False
3、S.isalnum()
判断字符串是不是全部为字母、中文、数字
res1 = ' '.isalnum()
res2 = 'aa11!'.isalnum()
res3 = 'aa11中国'.isalnum()
print(res1)
print(res2)
print(res3)
运行结果:
False
False
True
4、S.isupper()
判断字符串中包含的字母(可以不全是字母)是不是全大写
res1 = 'ABC'.isupper()
res2 = 'AbC'.isupper()
res3 = 'AB123!@#'.isupper()
print(res1)
print(res2)
print(res3)
运行结果:
True
False
True
5、S.islower()
判断字符串中包含的字母是否是全小写
res1 = 'Abc'.islower()
res2 = 'abc'.islower()
res3 = 'ab123!@#'.islower()
print(res1)
print(res2)
print(res3)
运行结果:
False
True
True
6、S.istitle()
判断是否只有首字母为大写
res1 = 'Abc'.istitle() # 只有首字母是大写,True
res2 = 'ABC'.istitle() # 都是大写,False
res3 = 'AbC'.istitle() # 末位是大写,False
res4 = 'Abc123!@#'.istitle() # 后面跟了非字母,前面满足条件True
res5 = 'A3C'.istitle() # 中间隔了非字母,后面可以大写开头了
res6 = 'A3CB'.istitle()
print(res1)
print(res2)
print(res3)
print(res4)
print(res5)
print(res6)
运行结果:
True
False
False
True
True
False
7、S.isdigit()
判断字符串是不是纯数字。注意,小数中有“.”,所以不算纯数字哦。复数有“-”,也不算纯数字
res1 = '12'.isdigit()
res2 = '12.1'.isdigit()
res3 = '-1'.isdigit()
res4 = '三'.isdigit()
print(res1)
print(res2)
print(res3)
print(res4)
运行结果:
True
False
False
False
8、S.isdecimal()
从字面意思看,是用来判断是不是小数。
实际上和“S.isdigit()”一样,都是判断是不是纯数字
res1 = '123'.isdecimal()
res2 = '1.1'.isdecimal()
res3 = '-1.1'.isdecimal()
res4 = '三'.isdecimal()
print(res1)
print(res2)
print(res3)
print(res4)
运行结果:
True
False
False
False
9、S.isnumeric()
判断是不是数字和中文数字。
res1 = '123'.isnumeric()
res2 = '1.1'.isnumeric()
res3 = '-1.1'.isnumeric()
res4 = '三万三千三百三十一'.isnumeric()
res5 = '叁'.isnumeric()
print(res1)
print(res2)
print(res3)
print(res4)
print(res5)
运行结果:
True
False
False
True
True
10、S.isidentifier()
方法用于判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法。
print( "if".isidentifier() )
print( "def".isidentifier() )
print( "class".isidentifier() )
print( "_a".isidentifier() )
print( "中国123a".isidentifier() )
print( "123".isidentifier() )
print( "3a".isidentifier() )
print( "".isidentifier() )
运行结果:
True
True
True
True
True
False
False
False
11、S.isprintable()
判断字符串中所有字符是否都是可打印字符(in repr())或字符串为空。
Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符(但不包括ASCII码中的空格(0x20))。可用于判断转义字符。
ASCII码中第0~32号及第127号是控制字符;第33~126号是可打印字符,其中第48~57号为0~9十个阿拉伯数字;65~90号为26个大写英文字母,97~122号为26个小写英文字母。
print('oiuas\tdfkj'.isprintable()) #制表符
print('oiuas\ndfkj'.isprintable()) #换行符
print('oiu.123'.isprintable())
print('oiu 123'.isprintable())
print('~'.isprintable())
print(''.isprintable())
运行结果:
False
False
True
True
True
True