【问题标题】:Python convert tuple into string [duplicate]Python将元组转换为字符串[重复]
【发布时间】:2018-11-11 05:48:26
【问题描述】:
date = [2, 5, 2018]
text = "%s/%s/%s" % tuple(date)
print(text)

它给出了结果2/5/2018。如何像02/05/2018一样转换它

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:
    text = "{:02d}/{:02d}/{:d}".format(*date) 
    

    【讨论】:

      【解决方案2】:

      使用 str.zfill(2) 用 2 个前导零填充您的日期片段:

      date = [2, 5, 2018]
      text = "%s/%s/%s" % tuple([str(date_part).zfill(2) for date_part in date])
      print(text) # Outputs: 02/05/2018
      

      【讨论】:

        【解决方案3】:
        date = [2, 5, 2018]
        text = "{:0>2}/{:0>2}/{}".format(*date)
        print(text)
        

        要了解有关使用 format 的更多信息,请阅读:https://pyformat.info/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-21
          • 1970-01-01
          • 2015-09-25
          • 2013-11-07
          • 2021-05-30
          • 1970-01-01
          • 1970-01-01
          • 2015-11-05
          相关资源
          最近更新 更多