python实验——字符串与列表的使用

1、通过用户输入的身份证号,输出对应的出生日期‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬程序运行的效果如下:‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬

请输入身份证号:320705199605230529

出生日期:1996年05月23日

import re
def get_birthdate(id_card):
    pattern = r'^\d{18}$'#只会匹配由18个数字组成的字符串
    if not re.match(pattern, id_card):
        return None
    # 身份证号的第7位到第14位是出生日期
    birthdate = id_card[6:14]
    year = birthdate[:4]
    month = birthdate[4:6]
    day = birthdate[6:]
    return f"{year}年{month}月{day}日"
# 用户输入身份证号
id_card = input("请输入身份证号:")
birthdate = get_birthdate(id_card)
if birthdate:
    print("出生日期是:", birthdate)
else:
    print("输入的身份证号无效")

2、自幂数是指一个n位数 (n≥3),它的每个位上的数字的n次幂之和等于它本身。例如153就是一个自幂(当n=3时也称为水仙花数),因为153=1^3+5^3+3^3。请按下面的运行结果找出用户输入范围内的所有自幂数。

t = int(input('请输入10的n次幂:(n>3)'))
n=10**t
print(f"{n}以内的自幂数包括:",n)
for i in range(100, n): 
    s = 0
    p = str(i)  
    for x in p:  
        s += int(x) ** len(p)  
    if s == i: 
        print(i)

3、对于给定的字符串"Where there is a will, there is a way. The important point is that you must have the will to achieve success.",请统计该字符串中不重复的单词数,并把这些单词按字母顺序降序排列,输出效果如下所示:

s = "Where there is a will, there is a way. The important point is that you must have the will to achieve success."
s = s.replace(".", " ").replace(","," ")
words = s.split() # 按空格分割单词
words = list(set(words)) # 去重
words.sort(reverse=True) # 排序
print("不重复的单词数有:", len(words))
print("单词按字母顺序降序排列:", words)

4、请按照教材教材第83页实训2中表3-5给出的数据完成食物菜单的建立与查询。建议使用一个列表存储食品大类,另一个列表存储各类食物的详细菜单。程序运行结果可以参考如下图:

words = []
menu=[]
while True:
    word = input("请输入食品大类:(输入q退出食品输入)")
    menu.append(word)
    if word.lower() == "q":
        break
    food=input(f"请输入{word}的详细食物菜单,多个食物直接用空格分开:")
    words.append(food)
menu=menu[0:-1]
print("当前的食品大类包括:",menu)
print("当前的详细食品菜单是:",words)
while True:
    s=int(input("请输入要查询的食品大类(输入0则退出程序):"))
    if s==0:
        break
    print(f"{menu[s-1]}食品的详细食物菜单是{words[s-1].split()}")

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值