python 中常用的字符串处理函数02
001、startswith、endswith:判定字符串是否以指定字符串开头或者结尾
>>> a = "abcdxyz" >>> a.startswith("a") ## 判定字符串是否以指定字符开头 True >>> a.startswith("b") False
>>> a = "abcdefxyz" >>> a.endswith("z") ## 判定字符串是否以指定字符结尾 True >>> a.endswith("y") False
002、expandtabs: 将字符串中的制表符转换为空格代替
>>> a = "abc\txyz" >>> a 'abc\txyz' >>> a.expandtabs() ##:将制表符转换为空格,默认是一个制表符为八个空格 'abc xyz' >>> a.expandtabs(tabsize = 2) 'abc xyz' >>> a.expandtabs(tabsize = 20) 'abc xyz'
003、find: 查找字符串中是否包含特定字符
>>> a = "abcdefg" >>> a.find("a") ## 查找字符串中是否包含特定字符,返回第一个位置的索引 0 >>> a.find("b") 1 >>> a.find("x") ## 如果字符不存在字符串中,返回-1 -1 >>> a.find("y") -1 >>> a.find("g") 6 >>> a.find("g", 0, 4) ## 可以指定查找的范围 -1
004、index:返回字符串中指定字符的索引
>>> a = "abcdefg" >>> a 'abcdefg' >>> a.index("a") ## index函数返回字符串中指定字符的索引 0 >>> a.index("d") 3 >>> a.index("x") ## 字符串中不存在指定的字符时,返回异常错误 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> a.index("g") 6 >>> a.index("g", 0, 4) ## 可以指定查找的范围 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
005、isalnum:判断字符串是否只有字母和数字组成。
>>> a = "abcd1234" >>> a.isalnum() ## 判断字符串是否只有字母和数字组成 True >>> b = "abcd,1234" >>> b.isalnum() False >>> c = "abcd" >>> c.isalnum() True >>> d = "1234" >>> d.isalnum() True >>>
006、isalpha: 判断字符串是否只有字母组成
>>> a = "abcd" >>> a.isalpha() ## 判断字符串是否只有字母组成 True >>> b = "1234" >>> b.isalpha() False >>> c = "abcd1234" >>> c.isalpha() False
007、 isdecimal:判断字符串是否只有数字(十进制)组成
>>> a = "1234" >>> a.isdecimal() ## 判断字符串是否只由数字组成 True >>> b = "abcd" >>> b.isdecimal() False >>> c = "12,34" >>> c.isdecimal() False
008、isdigit:判断字符串是否只有数字组成
>>> a = "1234" >>> a.isdigit() ## 判断字符串是否仅有数字组成 True >>> b = "abcd" >>> b.isdigit() False >>> c = "abcd1234" >>> c.isdigit() False
009、islower:判断字符串是否仅由小写字母组成
>>> a = "abcd" >>> a.islower() ## 判断字符串是否仅由小写字母组成 True >>> b = "ABCD" >>> b.islower() False >>> c = "abCD" >>> c.islower() False >>> d = "ab1234" >>> d.islower() True
010:isupper:判断字符串是否仅由大写字母组成
>>> a = "ABCD" >>> a.isupper() ## 判断字符串是否仅由大写字母组成 True >>> b = "abcd" >>> b.isupper() False >>> c = "ABcd" >>> c.isupper() False >>> d = "123,456" >>> d.isupper() False >>> e = "123,456AB" >>> e.isupper() True
011、isnumeric:判断字符串是否仅由数值组成
>>> a = "1234" >>> a.isnumeric() ## 判断字符串是否仅由数值组成 True >>> b = "abcd" >>> b.isnumeric() False >>> c = "34.24" >>> c.isnumeric() False
012、isspace:判断字符串是否仅由空白字符组成
>>> a = " " >>> a.isspace() ## 判断字符串是否都是有空白字符组成 True >>> b = " ab " >>> b.isspace() False >>> c = " , " >>> c.isspace() False

浙公网安备 33010602011771号