第五章(3) 字符串
本章主要内容:
一、字符串与前面介绍的列表、元组有相似之处
1、字符串分片
#字符串分片 str1 = " I love fishc.com!" a = str1[:6] print(a) #结果: I lov
2、字符串利用索引取值
#字符串利用索引取值 str1 = " I love fishc.com!" print(str1[5]) #结果: v
3、字符串的拼接
#字符串的拼接 str1 = " I love fishc.com!" b = str1[:6] + '插入的字符串' + str1[6:] print(b) # I lov插入的字符串e fishc.com!
#注意:这种拼接的方式是将变量指向了新的字符串b,旧的字符串str1还在
4、比较运算符、逻辑运算符、成员关系操作符等操作和列表元组一样,就不在啰嗦
二、各种内置方法
python字符串的方法:https://www.cnblogs.com/hcxy2007107708/articles/10004856.html
演示常用的方法
casefold()
#casefold() 把字符串的第一个字符改成大写 str1 = "Fishc" str1.casefold() print(str1) # Fishc
count(sub[,[start[,end]])
#查找sub子字符串出现的次数,可选参数 #python 中用方扩号(【】)扩起来表示可选 str1 = "AbcdABCabCabcABCabc" b = str1.count('ab',0,20) print(b) #结果:3
find(sub[,start[,end]]) 和 index()
#查找sub子字符串在字符串中的位置 str1 = "L love fishc.com" print(str1.find('fishc')) #结果 7 print(str1.find('good')) #结果 -1 #找不到会返回-1 print(str1.index('fishc')) #结果 7 print(str1.index('good')) #找不到,会抛出异常,ValueError: substring not found
join (连接字符串)
#join 是以字符串作为分隔符,插入到sub字符串中的所有字符之间 a = 'x'.join("Test") print(a) #结果 Txexsxt b = '_'.join('Fishc') print(b) #结果 F_i_s_h_c #使用join链接字符串效率比字符串拼接高 c = "I" + " " +"love" + " " +'fishc.com' print(c) #结果 I love fishc.com d = ' '.join(['I','love','fishc.com']) print(d) #结果 I love fishc.com
replace(old,new[,count])
#替换指定的字符串 str1 = "l love you" a = str1.replace("you","fishc.com") print(a) #结果 l love fishc.com print(str1) #还是原来的,没有变化
split(sep=None,maxsplit=-1)
#join链接字符串 str1 = " ".join(["l",'love','fishc.com']) print(str1) #l love fishc.com #拆分字符串 b = str1.split() #默认以空格拆分 print(b) #['l', 'love', 'fishc.com'] str2 = '_'.join("Fishc") bb = str2.split(sep='_') #sep="X" 自定义分割符 print(bb) #['F', 'i', 's', 'h', 'c']
如何判断一个字符串包含大写字母、数字、符号,可以参考
1 def len_s(z): #密码长度得分 2 a = len(z) 3 if 0 < a <= 4: 4 return 5 5 elif 5 <= a <=7: 6 return 10 7 elif a >= 8: 8 return 25 9 else: 10 return 0 11 12 def low_s(z): #字母大小写得分 13 b = str(z) 14 sb = 0 #小写字母个数 15 bb = 0 #大写字母个数 16 for i in b: 17 if i.islower(): 18 sb += 1 19 if i.isupper(): 20 bb += 1 21 if (sb != 0 and bb == 0) or (sb == 0 and bb != 0): 22 return 10 23 if sb != 0 and bb != 0: 24 return 20 25 else: 26 return 0 27 28 def num_s(z): #数字个数得分 29 c = str(z) 30 nc = 0 31 for i in c: 32 if i.isdigit(): 33 nc += 1 34 if nc == 1: 35 return 10 36 if nc > 1: 37 return 20 38 else: 39 return 0 40 41 def symbol_s(z): #符号存在得分 42 d = str(z) 43 nd = 0 44 symbol = "!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~" 45 for i in d: 46 if i in symbol: 47 nd += 1 48 if nd == 1: 49 return 10 50 if nd > 1: 51 return 25 52 else: 53 return 0 54 55 def get_x(z): #奖励得分 56 e = str(z) 57 se = 0 58 le = 0 59 for i in e: 60 if i.islower(): 61 se += 1 62 if i.isupper(): 63 le += 1 64 if ((se != 0 and le == 0) or (le != 0 and se == 0)) and num_s(e) != 0: 65 return 2 66 if ((se != 0 and le == 0) or (le != 0 and se == 0)) and num_s(e) != 0 and symbol_s(e)!= 0: 67 return 3 68 if (se != 0 and le != 0) and num_s(e) != 0 and symbol_s(e)!= 0: 69 return 5 70 else: 71 return 0 72 73 while True: 74 try: 75 f = str(input()) 76 score = len_s(f) + low_s(f) + num_s(f) + symbol_s(f) + get_x(f) 77 if score >= 90: 78 print("VERY_SECURE") 79 if 80 <= score < 90: 80 print("SECURE") 81 if 70 <= score < 80: 82 print("VERY_STRONG") 83 if 60 <= score < 70: 84 print("STRONG") 85 if 50 <= score < 60: 86 print("AVERAGE") 87 if 25 <= score < 50: 88 print("WEAK") 89 if 0 <= score < 25: 90 print("VERY_WEAK") 91 except: 92 break 93 94 95 #################################################################################### 96 while True: 97 try: 98 99 import re 100 101 102 def fun(pwd): 103 score = 0 104 # 规则一、密码长度: 105 if len(pwd) <= 4: 106 score += 5 107 elif 5<=len(pwd) <= 7: 108 score += 10 109 else: 110 score += 25 111 # 规则二、字母: 112 if re.findall('[a-z]', pwd) and re.findall('[A-Z]', pwd): 113 score += 20 114 elif re.findall('[a-z]', pwd) or re.findall('[A-Z]', pwd): 115 score += 10 116 else: 117 score += 0 118 # 规则三、数字: 119 #count = len(''.join(re.findall(r'\d+', pwd))) 120 count = len(re.findall(r'\d+', pwd)) 121 if count == 0: 122 score += 0 123 elif count == 1: 124 score += 10 125 else: 126 score += 20 127 # 规则四、符号: 128 count = len(''.join(re.findall('[^0-9a-zA-Z]', pwd))) 129 if count == 0: 130 score += 0 131 elif count == 1: 132 score += 10 133 else: 134 score += 25 135 # 规则五、奖励: 136 if re.findall('[a-z]', pwd) and re.findall('[A-Z]', pwd) and re.findall(r'\d+', pwd) and re.findall( 137 '[^0-9a-zA-Z]', pwd): 138 score += 5 139 elif re.findall('[a-zA-Z]', pwd) and re.findall(r'\d+', pwd) and re.findall('[^0-9a-zA-Z]', pwd): 140 score += 3 141 elif re.findall('[a-zA-Z]', pwd) and re.findall(r'\d+', pwd): 142 score += 2 143 # 判断等级 144 if score >= 90: 145 print('VERY_SECURE') 146 elif score >= 80: 147 print('SECURE') 148 elif score >= 70: 149 print('VERY_STRONG') 150 elif score >= 60: 151 print('STRONG') 152 elif score >= 50: 153 print('AVERAGE') 154 elif score >= 25: 155 print('WEAK') 156 elif score >= 0: 157 print('VERY_WEAK') 158 159 160 pwd = input() 161 fun(pwd) 162 except: 163 break
三、格式化(重点)
format
#format() 方法接受位置参数和关键字参数,二者均传递到一个叫作replacement 字段。 #这个replacement 字段在字符串内由大扩号({})表示 #方式一、位置参数 temp = "{0} love {1}.{2}".format("I","fishc","com") print(temp) #结果 I love fishc.com #方式二、关键字参数 temp2 = "{a} love {b}.{c} ".format(a="I",b="fishc",c="com") print(temp2) #结果 I love fishc.com #综合位置参数和关键字参数,位置参数必须在关键字之前 temp3 = "{0} love {a}.{b} ".format('I',a = 'Fishc',b = "com") print(temp3) #结果 I love fishc.com temp4= "{a} love {b}.{0} ".format(a="I",b="fishc","com") #会报错 print(temp4) """ #报错 temp4= "{a} love {b}.{0} ".format(a="I",b="fishc","com") ^ SyntaxError: positional argument follows keyword argument """
g = "{0}:{1:.2f} ".format("圆周率",3.14159) print(g) #结果:圆周率:3.14
结果分析:位置参数{1} 后面多了一个冒号。在替换域中,冒号表示格式化符号的开始,
“.2” 的意思是四舍五入到保留两位小数点,而f的意思是浮点数,所以打印的结果是3.14
四、格式化操作符: %
字符串格式化符号含义及转义字符含义:https://www.cnblogs.com/hcxy2007107708/articles/10091916.html
举例一
字符串格式化符号含义
|
符号
|
说明
|
|
%c
|
格式化字符及其 ASCII 码 |
|
%s
|
格式化字符串 |
|
%d
|
格式化整数 |
|
%o
|
格式化无符号八进制数(小写的欧) |
|
%x
|
格式化无符号十六进制数 |
|
%X
|
格式化无符号十六进制数(大写) |
|
%f
|
格式化浮点数字,可指定小数点后的精度 |
|
%e
|
用科学计数法格式化浮点数 |
|
%E
|
作用同 %e,用科学计数法格式化浮点数 |
|
%g
|
根据值的大小决定使用 %f 或 %e |
|
%G
|
作用同 %g,根据值的大小决定使用 %f 或者 %E |
#格式化字符 print('%c' %97) #a #格式化整数 print("%c%c%c%c%c" % (70,105,115,104,67)) a = "%c%c%c%c%c" % (70,105,115,104,67) print(a) #FishC #格式化无符号八进制数 b = '%d转换为八进制是:%o'% (123,123) #小写的“o"字母 print(b) #123转换为八进制是:173 #格式化浮点数字 c = "%f 用科学计数法表示为:%e" %(149500000,149500000) print(c) #149500000.000000 用科学计数法表示为:1.495000e+08
举例二
格式化操作符辅助命令
|
符号
|
说明
|
|
m.n
|
m 是显示的最小总宽度,n 是小数点后的位数 |
|
-
|
用于左对齐 |
|
+
|
在正数前面显示加号(+) |
|
#
|
在八进制数前面显示 '0o',在十六进制数前面显示 '0x' 或 '0X' |
|
0(零)
|
显示的数字前面填充 '0' 取代空格 |
#格式化浮点数,指定小数点后保留一位 a = '%5.1f'% 27.658 print(a) # 27.7 #e计法 b = '%.2e'% 27.658 #保留小数点后两位 print(b) #2.77e+01 c = '%10d'% 5 #10为宽度,在5前面补9个0,总共10位 print(c) # 5 d = '%-10d'%5 #‘-’表示结果左对齐, 宽度为10,后面补9个0 print(d) #5 | E = "%010d" % 5 #用0代替空格,10表示宽度为10位,不足补0 print(E) #0000000005 F= '%#x'%100 # 小写“x",表示16进制 FF= '%#X'%100 # 大写“X",表示16进制 print(F) print(FF) #0X64 #0X64 H = '%d的八进制%#o'%(123,123) #'#"表示在八进制数前显示‘0o’ print(H) #123的八进制0o173 HH = '%d的十六进制%#X'%(123,123) #'#"表示在十六进制数前显示‘0X’ print(HH) #123的十六进制0X7B 大写X Hx = '%d的十六进制%#x'%(123,123) #'#"表示在十六进制数前显示‘0x’ print(Hx) #123的十六进制0x7B 小写X
五、作业
[课后作业] 第014讲:字符串:各种奇葩的内置方法 | 课后测试题

浙公网安备 33010602011771号