【问题标题】:Manipulating an array of strings and replacing them操作字符串数组并替换它们
【发布时间】:2020-05-13 09:41:40
【问题描述】:

这是一个涉及字符串操作的问题。 例如

unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]

我现在想将“一月”替换为 1,将“二月”替换为 2,依此类推。我还需要删除两者之间的空格和分隔符。 我怎样才能做到这一点?

【问题讨论】:

    标签: python arrays string data-manipulation


    【解决方案1】:
    from datetime import datetime
    unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]
    ans = []
    for val in unique_dates:
      objDate = datetime.strptime(val, '%B %d,%Y')
      ans.append(objDate.strftime('%d/%m/%Y'))
    print(unique_dates, ans)
    
    

    在 python 中引用 datetime 模块

    【讨论】:

      【解决方案2】:

      首先使用strptime 转换为时间对象,然后使用strftime 转换为所需的字符串。可以在一行中完成:

      from time import strptime, strftime
      
      unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]
      
      [strftime('%d/%m/%Y', strptime(i, '%B %d,%Y'))  for i in unique_dates]
      >>> ['12/01/1988', '11/02/1995', '02/12/1992']
      

      【讨论】:

        猜你喜欢
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 2016-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        相关资源
        最近更新 更多