No3.字符串的魔法

1 >>> test = "trony"
2 >>> v = test.capitalize()
3 >>> print(v)
4 Trony
字符串首字母大写
 1 >>> test = "ASDFG"
 2 >>> v = test.casefold()
 3 >>> print(v)
 4 asdfg
 5 
 6  7 
 8 >>> test = "ASDFG"
 9 >>> v = test.lower()
10 >>> print(v)
11 asdfg
12 
13 区别:casefold()和lower()方法都是将字符串变小写,casefold()更牛逼它可以将许多未知的字符串变小写
字符串大写变小写
 1 >>> test = "trony"
 2 >>> v = test.center(20)
 3 >>> print(v)
 4        trony        
 5 
 6 -----------------------------为了效果-----------------------------------
 7 
 8 >>> v2 = test.center(20, "*")
 9 >>> print(v2)
10 *******trony********
11 
12 用法:center()方法设置宽度并将内容居中,第二个参数只能带一个字符默认为空
字符串居中
 1 >>> test = "tronytrony"
 2 >>> v = test.count("o")
 3 >>> print(v)
 4 2
 5 >>> v2 = test.count("o", 5, 6)
 6 >>> print(v2)
 7 0
 8 >>> v3 = test.count("tr")
 9 >>> print(v3)
10 2
11 
12 用法:count()计算当前当前字符序列的出现次数,后面参数可以指定范围
计算当前字符序列的出现次数
 1 >>> test = "tronytrony"
 2 >>> v = test.endswith("t")
 3 >>> print(v)
 4 False
 5 >>> v2 = test.endswith("y")
 6 >>> print(v2)
 7 True
 8 >>> v3 = test.endswith("ny")
 9 >>> print(v3)
10 True
11 >>> v4 = test.endswith("r", 0, 2)
12 >>> print(v4)
13 True
14 
15 用法:endswith()以什么结尾,startswith()以什么开始,可指定范围
某序列以什么开头
 1 >>> test = "tronytrony"
 2 >>> v = test.find("o")
 3 >>> print(v)
 4 2
 5 >>> v2 = test.find("o", 0, 3)
 6 >>> print(v2)
 7 2
 8 >>> v3 = test.find("e")
 9 >>> print(v3)
10 -1
11 >>> v4 = test.find("on")
12 >>> print(v4)
13 2
14 
15 用法:从开始往后找,找到第一个之后,获取其位置,可指定范围,若没有则返回-1
查找字符符列
 1 >>> test = "i am {name}, age {a}"
 2 >>> v1 = test.format(name="trony", a=19)
 3 >>> print(v1)
 4 i am trony, age 19
 5 >>> test2 = "i am {0}, age {1}"
 6 >>> v2 = test2.format("trony", 19)
 7 >>> print(v2)
 8 i am trony, age 19
 9 
10 11 
12 >>>test3 = "i am {name}, age{a}"
13 >>> v3 = test3.format_map({"name":"trony", "a":19})
14 >>> print(v3)
15 i am trony, age19
16 
17 区别:二者类似,不过format_map()传入的参数是字典形式
格式化输入
 1 >>> test = "tronytrony"
 2 >>> v = test.index("o")
 3 >>> print(v)
 4 2
 5 >>> v2 = test.index("w")
 6 Traceback (most recent call last):
 7   File "<pyshell#3>", line 1, in <module>
 8     v2 = test.index("w")
 9 ValueError: substring not found
10 
11 建议:使用count方法
查找字符序列出现的次数
1 >>> test = "trony123"
2 >>> v1 = test.isalnum()
3 >>> print(v1)
4 True
5 >>> test2 = "trony++121"
6 >>> v2 = test2.isalnum()
7 >>> print(v2)
8 False
判断字符串中是否只包含数字和字母

 未完待续。。。

猜你喜欢

转载自www.cnblogs.com/Tronyshi/p/9120197.html
今日推荐