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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-05-22 c语言 8-8 求最大公约数
2021-05-22 c语言 8-7
2021-05-22 c语言 8-6
2021-05-22 c语言中利用递归求非负整数的阶乘
2021-05-22 c语言 8 - 5
2021-05-22 c语言 8-4
2021-05-22 c语言中枚举类型