You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效检查多格式月份输入并转为数字?求代码优化方案

优化后的月份解析方案

我来帮你把这个月份转换函数改得更简洁清爽,同时保持功能完整~下面是优化后的实现:

from datetime import datetime

def parse_month_input(month_str):
    # 先尝试解析数字格式
    if month_str.isdigit():
        month_num = int(month_str)
        return month_num if 1 <= month_num <= 12 else None
    
    # 尝试解析月份名称/缩写
    for fmt in ('%b', '%B'):
        try:
            return datetime.strptime(month_str.strip(), fmt).tm_mon
        except ValueError:
            continue
    # 所有格式都匹配失败
    return None

def get_start_month_updated():
    while True:
        month_input = input("What is the starting month? ").strip()
        month_num = parse_month_input(month_input)
        if month_num is not None:
            return month_num
        print("You must enter a valid month (e.g. 3, Mar, March)")

优化亮点:

  • 职责拆分:把月份解析逻辑单独抽成parse_month_input函数,主函数只负责循环输入和结果判断,代码结构更清晰,后续修改解析规则只需要调整辅助函数就行
  • 扁平结构:去掉了原代码里嵌套的try-except,逻辑层级更直观,可读性更高
  • 移除空pass:用continue替代无意义的pass,明确表示“继续尝试下一种格式”
  • 统一错误提示:原代码里有两处重复的错误打印,现在只在一处处理,避免冗余
  • 输入预处理:增加了.strip()处理输入的前后空格,用户不小心输入空格也能正常解析

内容的提问来源于stack exchange,提问作者ShockDoctor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:40:03