【问题标题】:what is the index of second "/" in 12/25/2009?2009 年 12 月 25 日第二个 \"/\" 的索引是多少?
【发布时间】:2023-01-20 00:08:28
【问题描述】:

`日期中第二个“/”的索引是什么。

  date = input('write todays date: ')
  i  = date.find('/')

  month = date\[:i]
  day =??????
  year = ???????
  print(f' todays month is {month}')

我尝试了我所有的知识都没有用`

【问题讨论】:

  • 我建议使用适当的日期库而不是自己处理解析。例如你可以使用datetime.datetime.strptime(date, '%m/%d/%Y')
  • 我同意@0x5453。如果您想知道如何使用字符串,您也可以这样做:month, day, year = date.split("/") 否则,直接回答您的问题第二个“/”的索引 si 5
  • 你也可以使用date.split('/'),它会给你一个列表,你只需索引你想要的元素

标签: python


【解决方案1】:

Python 方法 find 采用可选参数。您可以通过起始索引来查找。在您的情况下,开始将是第一场比赛的结束索引。

例子:

first = date_str.find("/")
if (first == -1):
     # not found
second = date_str.find("/", first + 1)
...

【讨论】:

    【解决方案2】:

    我建议你使用datetime来执行解析和格式化,在这种情况下使用datetime.strptime

    >>> from datetime import datetime
    >>> dt = datetime.strptime('12/25/2009', '%m/%d/%Y')
    >>> dt
    datetime.datetime(2009, 12, 25, 0, 0)
    >>> dt.month, dt.day, dt.year
    (12, 25, 2009)
    

    【讨论】:

      【解决方案3】:

      如果我正确理解你的问题,如果你将该字符串视为基于零的数组,则该日期格式中的第二个“/”将是索引 2。

      所以我说...2个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 2019-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多