【问题标题】:How to change month name to a number?如何将月份名称更改为数字?
【发布时间】:2019-09-21 21:50:56
【问题描述】:

我这个月开始学习 python。我是初学者,所以在将月份名称更改为数字时遇到问题。我尝试使用if 命令,但它不起作用。

我使用的代码是:

d = int(input())
m = input()
y = int(input())
a = y - 1900

if m == january:
    x = 1

print(f'It is {d} days, {x} months and {a} years at {d m y}.')

但它不起作用,程序显示名称 january 未定义。如何将月份名称更改为数字?

【问题讨论】:

标签: python


【解决方案1】:

您的一月不在引号中,因此 Python 将其读取为变量。应该是m == ‘January’ 才能让它工作。

【讨论】:

    【解决方案2】:

    你应该使用 strptime 模块。

    例如:

    from time import strptime
    input_month = 'January'
    input_month = input_month[:3]
    strptime(input_month,'%b').tm_mon
    

    【讨论】:

      【解决方案3】:

      程序显示名称 january 未定义

      为了解释,Python 查看您的程序并需要知道哪些是variables,哪些是strings。当您使用不带引号 (') 的 january 时,Python 解释器认为您想使用 january 作为变量。它查找january 变量,但找不到它,因为它不存在。

      您需要的可能是将 m.lower() 与字符串进行比较,一月。为此,您只需将 january 括在单引号 (') 或双引号 (") 中(Python 都接受)。

      该行将如下所示:

      if m == 'january':

      希望有帮助!

      【讨论】:

        【解决方案4】:

        if m.lower() == "january":

        • january 是一个变量,但你需要一个字符串:"january"
        • 要使用户输入不区分大小写,请使用m.lower():将所有输入字符转换为小写

        要考虑所有月份,并触发用户输入有效的输入(如果无效),您可以紧凑地执行以下操作:

        months_indices = {"january":1, "february":2, "march":3, "april":4, "may":5, "june":6,
               "july":7, "august":8, "september":9, "october":10, "november":11, "december":12}
        
        while m.lower() not in months_indices:
            m = input("Please enter a valid month")
        x = months_indices[m.lower()] # index into a dictionary to return one of 1,2,...,12
        

        【讨论】:

          【解决方案5】:

          我也认为字典是个好主意:

          d = int(input('Please enter an integer for days:\t'))
          m = input('Please enter the lowercase name of the month:\t')
          y = int(input('Please enter an integer for the year:\t'))
          a = y - 1900
          
          months = {'january': 1, 'february': 2}
          
          for index, item in enumerate(months):
              if m == item.lower():
                  print(f'It is {d} days, {months[item]} months and {a} years at {d} {m} {y} .')
              break
          

          【讨论】:

            【解决方案6】:

            最后一段去掉括号后的'f'

            【讨论】:

            • 那是f-string,详情请咨询here
            猜你喜欢
            • 2015-09-09
            • 1970-01-01
            • 2018-09-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-02
            • 1970-01-01
            相关资源
            最近更新 更多