- 实验目的:
- 实验内容:
了解字符串编码规则,掌握字符串的切片和索引、掌握
字符串常用方法,能够使用正则表达式匹配指定的字符
串,能够熟练应用re库中的常用方法。
- 字符串格式化
有下面两个元组(‘李晨’,‘刘勇’,‘赵雪’,‘王峰’)和
(89,92,76,65),使用字符串格式化的方法,输出下面的结果。:
李晨的成绩为:89
刘勇的成绩为:92
赵雪的成绩为:76
王峰的成绩为:65
a=('李晨','刘勇','赵雪','王峰')
b=(89,92,76,65)
for i in range(0,4):
print(f"{a[i]}的成绩为:{b[i]}")//方法1
print("%s的成绩为:%d"%(a[i],b[i]))//方法2
//方法3
print("%s的成绩为:%d"%(a[0],b[0]),"%s的成绩为:%d"%(a[1],b[1]),"%s的成绩为:%d"%(a[2],b[2]),"%s的成绩为:%d"%(a[3],b[3]),sep='n')
- 使用random库和string库,随机生成车牌号码陕A*****,
前4位是数字,最后一位是大写字母。效果如下:陕A8226Q
import random
import string
print("下面将生成随机车牌号码")
print("陕A %d%d%d%d%s"%(random.randint(0,10),random.randint(0,10),
random.randint(0,10),random.randint(0,10),random.choice(string.ascii_uppercase)))
- 下面这段英文中,单独的字母I误写为i,用正则表达式的方法进行纠正。
“i never give up,i never lose hope.Always have faith,It allows you to cope.”
import re s = "i never give up,i never lose hope.Always have faith,It allows you to cope." new_s=re.sub(r'bib','I',s) print(new_s)
- 在"NevergIveup!"这个英文句子中,give中间的字母i误写为I,
用正则表达式的方法进行纠正。
import re s="NevergIveup!" new_s= re.sub(r'I','i',s) print(new_s)
- 将“Today is a nice day.”这句英语文本中的单词进行倒置,标点不倒置。
经过倒置后变为:“Day nice a is today.”
import re
s = "Today is a nice day."
print(" ".join(reversed(s.rstrip(".").split())).lower().capitalize()+".")
- 输出下面这段英文中所有长度为4个字母的英文单词。
import re
x = "Never give up,Never lose hope.Always have faith,It allows you to cope."
re_str = r'[a-zA-Z]{4}'
print(re.findall(re_str,x))//方法1
pattern = re.compile(r"[a-zA-Z]{4}")
print(pattern.findall(x))//方法2



