人生苦短,我用Python,坚持每日分享,今天再分享10个Python字符串函数!
1.isdecimal():
判断是否为数字,可以判断阿拉伯数字,判断不了字节数字和汉字数字
>>> n1 = '8' >>> n2 = b'8' >>> n3 = '八' >>> n1.isdecimal() True >>> n2.isdecimal() Traceback (most recent call last): File "", line 1, in AttributeError: 'bytes' object has no attribute 'isdecimal' >>> n3.isdecimal() False
2.isdigit():
判断是否为数字,可以判断阿拉伯数字和字节数字,判断不了汉字数字
>>> n1 = '8' >>> n2 = b'8' >>> n3 = '八' >>> n1.isdigit() True >>> n2.isdigit() True >>> n3.isdigit() False
3.isnumeric():
判断是否为数字,可以判断阿拉伯数字和汉字数字,判断不了阿拉伯数字
>>> n1 = '8' >>> n2 = b'8' >>> n3 = '八' >>> n1.isnumeric() True >>> n2.isnumeric() Traceback (most recent call last): File "", line 1, in AttributeError: 'bytes' object has no attribute 'isnumeric' >>> n3.isnumeric() True
4.isidentifier():
判断是否为合法的标识符
>>> s = '8apple' >>> s.isidentifier() False >>> s = 'apple8' >>> s.isidentifier() True
5.islower():
判断字符串中的字母是否全部为小写字母,数字和其他符号不影响
>>> s = 'Abcde' >>> s.islower() False >>> s = 'abcde' >>> s.islower() True >>> s = 'abc34$' >>> s.islower() True
6.isascii():
判断是否全部为ASCII字符
>>> s = 'abcd568' >>> s.isascii() True >>> s = 'abcd56哈哈' >>> s.isascii() False
7.isspace():
判断是否为空格
>>> s = '' >>> s.isspace() False >>> s = ' ' >>> s.isspace() True
8.istitle():
判断是否为有且仅有首字母为大写的字符串
>>> s = 'Abcdeg' >>> s.istitle() True >>> s = 'abcdg' >>> s.istitle() False >>> s = '123abc' >>> s.istitle() False >>> s = 'AAAA' >>> s.istitle() False >>> s = 'abcdgGG' >>> s.istitle() False >>> s = 'AAbcd56' >>> s.istitle() False >>> s = 'A123' >>> s.istitle() True
9.isupper():
判断字符串中的字母是否全部为大写字母,只要有一个小写字母就返回False,有数字和其他符号没关系
>>> s = 'ABCDE' >>> s.isupper() True >>> s = 'abCDE' >>> s.isupper() False >>> s = 'ABCD2' >>> s.isupper() True >>> s = 'ABCD$' >>> s.isupper() True
10.isprintable():
判断是否为可打印的字符串
>>> s = b'67' >>> s.isprintable() Traceback (most recent call last): File "", line 1, in AttributeError: 'bytes' object has no attribute 'isprintable' >>> s = '67ad' >>> s.isprintable() True
以上所有代码基于Python3.10测试



