19、python基础学习-字符串及操作

 1 #!/usr/bin/env python
 2 #__author: hlc
 3 #date: 2019/5/26
 4 # 字符串是以单引号'或者双引号"括起来的任意文本,例如:'asd',"123"
 5 # '"不是字符串的一部分,如果需要作为字符串的一部分,需要在单引号外面加上双引号,如:"it's a Good !"
 6 
 7 #创建字符串
 8 # var1 = "Hello word"
 9 # var2 = 'python book'
10 
11 #字符串操作
12 # 重复输出字符串
13 # print("hello"*2) #hellohello
14 #通过索引获取字符串中的字符
15 # print("hello"[2:]) # llo
16 #判断成员
17 # print("he" in "hello") # True
18 # print("he1" in "hello") # False
19 #格式化字符串
20 # name = "asd"
21 # print("your name is %s !"% name) #your name is asd !
22 #字符串拼接
23 # a = "qwe"
24 # b = "456"
25 # c = "uio"
26 # print(a+b) # qwe456,使用"+"进行拼接,效率低
27 #
28 # print(''.join((a,b,c))) # qwe456uio ,效率高
29 # print('------'.join((a,b,c))) # qwe------456------uio
30 
31 # 字符串的内置方法
32 # st = "hello kitty"
33 # print(st.count("l")) # 2 ,统计元素个数
34 # print(st.capitalize()) # Hello kitty , 首字母大写
35 # print(st.center(20,"#")) # 将内容居中,其他用指定字符填充
36 # print(st.endswith("tty")) # True ,判断以某个内容结尾
37 # print(st.startswith("hell")) # True ,判断以某个内容开头
38 # st = "he\tllo kitty"
39 # print(st.expandtabs(20)) # he                  llo kitty ,将\t替换为指定的空格
40 # print(st.find("t")) # 8 ,查找到第一个元素,并将索引值返回,没有返回 -1
41 # st = "hello kitty {num} {sam}"
42 # print(st.format(sam = 100,num = 200)) # hello kitty 100 200 ,格式化输出
43 # print(st.format_map({"num":100,"sam":200})) # hello kitty 100 200 ,格式化输出
44 # print(st.index("t")) # 8,查找到第一个元素,并将索引值返回,和find相比,没有会报错
45 # print(st.isalnum()) # False 判断是否为字符串,数字,汉字
46 # print(st.isalnum()) # False 判断是否为字符串,数字,汉字
47 # print(st.isdecimal()) # False 判断是否为十进制
48 # print("1234".isdigit()) # True 判断是否为整数
49 # print("123.4".isdigit()) # False 判断是否为整字
50 # print("123.4".isnumeric()) # False 判断是否为整字,和isdigit功能一样
51 # print("Asd".islower()) # False 判断是否为全小写
52 # print("Asd".isupper()) # False 判断是否为全大写
53 # print(" ".isspace()) # True 判断是否为空格
54 # print("Asd Tre".istitle()) # True 判断是否为标题,首字母大写
55 # a = "ads"
56 # b = "456"
57 # print("".join((a,b))) # ads456 字符串拼接,效率高
58 # print("Asd Tre".upper()) # ASD TRE 变为大写
59 # print("Asd Tre".swapcase()) # asd tre 大小写反转
60 # print("Asd Tre".ljust(20,"#")) # Asd Tre############# ,靠右填充
61 # print("Asd Tre".rjust(20,"#")) # #############Asd Tre ,靠左填充
62 # print("   \tAsd Tre\n".strip()) # Asd Tre ,去掉前面或后面的空格,换行,制表符
63 # print("   \tAsd Tre\n".lstrip()) # Asd Tre ,去掉前面的空格,换行,制表符
64 # print("   \tAsd Tre\n".rstrip()) # Asd Tre ,去掉后面的空格,换行,制表符
65 # print("Asd Tre".replace("Tre","789")) # Asd 789 ,替换字符串
66 # print("Asd Tre Tre".replace("Tre","789",1)) # Asd 789 Tre ,替换字符串,替换1次
67 # print("Aesd Tre".rfind("e")) # 7 ,从右向左查找
68 # print('Asd Tre asdfk'.split(' ')) # ['Asd', 'Tre', 'asdfk'] 以空格为分隔对象
69 # print('Asd Tre asdfk'.split('s')) # ['A', 'd Tre a', 'dfk'] 以"s"为分隔对象
70 # print('Asd Tre asdfk'.split('s',1)) # ['A', 'd Tre asdfk'] 以"s"为分隔对象,从左边开始分割1次
71 # print('Asd Tre asdfk'.rsplit('s',1)) # ['Asd Tre a', 'dfk'] 以"s"为分隔对象,从右边开始分割1次
72 # print('asd tre asdfk'.title()) # Asd Tre Asdfk ,首字母变成大写

猜你喜欢

转载自www.cnblogs.com/hlc-123/p/10926642.html