4.字符串格式
-
编写程序,已知字符串s = "AbcDeFGhIJ",请计算该字符串中小写字母的数量。
s = 'AbcDeFGhIJ' num = 0 # 统计英文字母个数 for i in range(len(s)): # 利用字符ASCII码中的位逐个统计 if "a" <= s[i] <= "z": num += 1 print("小写字母的个数为:%d" % num) s = "AbcDeFGhIJ"
输出结果:
小写字母的个数为:4
方法二:
s = "AbcDeFGhIJ" count = 0 for i in s: # print(i, "=", ord(i)) # print(ord('a'), ord('z')) if ord(i) >= 97 and ord(i) <= 122: count = count + 1 print("小写字符数量为", count) s = "AbcDeFGhIJ" count = 0 for i in s: for j in s.lower(): if i == j: count = count + 1 print("小写字符数量为", count)
-
编写程序,检查字符串" Life is short. I use python"中是否包含字符串"python",若包含则替换为"Python"后输出新字符串,否则输出原字符串。
# coding = utf-8 # 创建一个字符串circle source_string = " Life is short. I use python" if 'python' in source_string: # 利用replace()方法用子串"Python"代替子串"python" print(source_string.replace('python', 'Python')) else: print(" Life is short. I use python")
输出结果:
Life is short. I use Python
-
现在有个字符串是按照如下格式保存的:“姓名:成绩|姓名:成绩|…..”,例如:张三:90|李四:88|王五:100;要求将字符串变为如下的形式显示:“姓名:张三,成绩:90”,显示后的数据如下图所示,按不同的人员显示。
# 程序一 str1 = "张三:90" str2 = "李四:88" str3 = "王五:100" Str = str.split("\\|") print("姓名:" + str1.split(":")[0] + ",成绩:" + str1.split(":")[1]) print("姓名:" + str2.split(":")[0] + ",成绩:" + str2.split(":")[1]) print("姓名:" + str3.split(":")[0] + ",成绩:" + str3.split(":")[1]) # 程序二 str = "张三:90|李四:88|王五:100" print("姓名:", str[0 :2], "成绩:", str[3 :5]) print("姓名:", str[6 :8], "成绩:", str[9 :11]) print("姓名:", str[12 :14], "成绩:", str[15 :18]) # 程序三 str = '张三:90|李四:88|王五:100' res = ['姓名:{0},成绩:{1}'.format(x.split(':')[0],x.split(':')[1]) for x in str.split('|')] for x in res: print(x) # 程序四 s= "张三:90|李四:88|王五:100" s1 = s.split("|") for i in s1: b = i .split(":") print("姓名:{0}, 成绩:{1}".format(b[0], b[1]))
输出结果:
姓名:张三,成绩:90 姓名:李四,成绩:88 姓名:王五,成绩:100