【问题标题】:Converting a month name to the corresponding number. (Python)将月份名称转换为相应的数字。 (Python)
【发布时间】:2021-02-26 03:33:00
【问题描述】:

我对编码非常陌生,目前正在处理这个问题。

print("What month were you born?")
m = input()

print("What day were you born?")
d = input()

print("What year were you born?")
y = input()

print("Your birthday is " + m + "/" + d + "/" + y)

如果我输入 2000 年 1 月 1 日作为我的生日,我会得到 2000 年 1 月 1 日,但我想要的输出是 2000 年 1 月 1 日。有什么建议吗?

【问题讨论】:

  • 结帐日期时间模块
  • 为什么要求用户分别输入月份名称和日期组件?如果他们打错了怎么办?为什么不简单地以特定格式询问出生日期,例如YYYY-MM-DD?

标签: python


【解决方案1】:

您需要一种将月份名称映射到代表月份的数字的方法。这可以通过列表或字典来完成。下面我们列出了月份。代表那个月份的数字就是列表中月份的索引+1:

print("What month were you born?")
m = input()

print("What day were you born?")
d = input()

print("What year were you born?")
y = input()

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

print("Your birthday is " + str(months.index(m)+1) + "/" + d + "/" + y)

您可以在此基础上添加代码以使输入不区分大小写并在用户输入错误值时捕获异常。

【讨论】:

  • 它完全符合我的要求,谢谢。
  • 太棒了。欢迎来到堆栈溢出。如果它解决了您的问题,请考虑接受答案。这是关于 SO 的礼仪:stackoverflow.com/help/someone-answers
【解决方案2】:
print("What month were you born?")
m = input()
newm = 'lol'
if m == "January" or "january":
    newm = '1'
if m == "February" or "february":
    newm = '2'
#KEEP GOING TILL DECEMBER

print("What day were you born?")
d = input()

print("What year were you born?")
y = input()

print("Your birthday is " + newm + "/" + d + "/" + y)

这里的其他 cmet 提出的建议不在你的技能水平上。我认为这以一种您可以理解正在发生的事情的方式回答了您的问题。

当你变得更好时,会有更好的方法来做这件事,就像其他 cmets 所建议的那样。有更好的方法来做这个代码大声笑,比如在一月/一月忽略大小写。

【讨论】:

  • 无论我放什么,我都只得到了 2 个月份,谢谢你,另一个用户发布了一些有用的东西。
【解决方案3】:

这个问题以前有人问过,也有很多回答。这是该 stackoverflow 问题的链接。尝试使用那里的一些解决方案。

month name to month number and vice versa in python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2012-11-26
    • 2018-06-11
    • 1970-01-01
    • 2016-10-04
    • 2011-03-18
    相关资源
    最近更新 更多