字符串魔法
1.首字母大写功能
test = "alex" v = test.capitalize() print(v)
2.所有变小写(casefold更厉害,可以将很多未知的其他国家字符变小写)
test = "ALex" v1 = test.casefold() print(v1) v2 = test.lower() print(v2)
3.设置宽度,并将内容居中,20代指总长度,*为空白位置填充一个字符,可有可无。
test = "alex" v = test.center(20, "*") print(v)
4.统计某字符出现的次数,可以设置起始和结束位置,可以不设置
test = "alexalexr" v = test.count(‘ex‘,5,8) print(v)
5.判断以什么什么结尾或开始,也可以指定起始和结束位置
test = "alex" v1 = test.endswith(‘x‘) v2 = test.startswith(‘b‘) print(v1) print(v2)
6.将/t转换为指定空格,默认为8个
test = "alex\tdabai" v = test.expandtabs(16) print(v)
7.从开始往后找,找到第一个后,获取其位置,找不到的话返回 -1,可以指定起始和结束位置
test = "alexalex" v1 = test.find("ex") v2 = test.find("ex", 5, 7) print(v1) print(v2)
8.格式化,将字符串中的占位符替换为指定的值
test1 = "i am {name}" print(test1) v1 = test1.format(name = ‘alex‘) print(v1) test2 = "i am {0},age{1}" print(test2) v2 = test2.format(‘Iro man‘,35) print(v2)
9.和8效果一样,传入的值为字典类型
test = "i am {name},age{a}" v = test.format_map({"name":"Iro man", "a":35}) print(v)
10.和find功能一样,但是找不到会报错,可忽略,建议用find
test = "alexalex" v1 = test.index("ex") print(v1) v2 = test.index(‘8‘) print(v2)
11.判断字符串是否只包含字母和数字,有别的字符会报False
test1 = "asdfhisa123" test2 = "[email protected]$s2_^" v1 = test1.isalnum() v2 = test2.isalnum() print(v1) print(v2)
未完待续
原文地址:https://www.cnblogs.com/dabai123/p/10926035.html
时间: 2024-10-30 10:30:44