求助:Python实现三次输入多周几字符串并验证输入有效性
Python实现带验证的星期几输入收集
直接上可运行代码,完全满足需求:
VALID_DAYS = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'} result_lists = [] for list_num in range(1, 4): while True: raw_input = input(f"Please enter the day(s) of the week (List {list_num}): ") # 处理输入:兼容逗号/空格分隔,清理空白内容 input_items = [item.strip() for item in raw_input.replace(',', ' ').split() if item.strip()] # 检查无效输入 bad_entries = [day for day in input_items if day not in VALID_DAYS] if not bad_entries: result_lists.append(input_items) break print(f"Invalid entries: {', '.join(bad_entries)}. Use exact spellings: {', '.join(VALID_DAYS)}") # 赋值为示例中的变量名 List1, List2, List3 = result_lists print(f"List1 = {List1}") print(f"List2 = {List2}") print(f"List3 = {List3}")
代码说明
- 输入兼容:支持用户用逗号加空格(
Monday, Wednesday)或纯空格(Monday Wednesday)分隔多个日期,自动过滤空内容 - 严格验证:仅接受指定的7个大小写规范的星期几,任何拼写错误或大小写不符都会被识别为无效
- 循环校验:如果输入无效,会反复提示用户重新输入,直到内容全部合法
- 结果输出:最终生成的三个列表完全匹配给出的示例格式
测试样例
Please enter the day(s) of the week (List 1): Monday, Wednesday, Friday Please enter the day(s) of the week (List 2): Tuesday Friday Please enter the day(s) of the week (List 3): Wednesday List1 = ['Monday', 'Wednesday', 'Friday'] List2 = ['Tuesday', 'Friday'] List3 = ['Wednesday']
内容的提问来源于stack exchange,提问作者dwburger
相关产品推荐
相关产品推荐

