【问题标题】:Issue with formating element of list on 2 places2个地方的列表格式元素问题
【发布时间】:2022-01-08 21:57:07
【问题描述】:

我正在尝试在 2 个地方格式化我的数据。如果它只包含 1 个元素,它应该附加 0 到它。例如new_time = [10,52]我的愿望输出是[10,52] For [10,5] 我的愿望输出是[10,05] 我读到了这个方法new_time = [new_time[0],new_time[1]:02]。但是这个的输出是无效的语法。有谁知道为什么它不起作用?我做了类似的练习,效果很好。

【问题讨论】:

  • 请展示您正在使用的代码示例以及您获得的输出。
  • 您的问题解决了吗?

标签: python list format element


【解决方案1】:

整数不可能用前导零表示,这是设计使然。 尝试在您的 python 控制台中运行此语句: print(05)。你会得到一个错误说明

SyntaxError: leading zeros in decimal integer literals are not permitted; 
use an 0o prefix for octal integers

但如果需要,您可以将整数类型转换为字符串并在逻辑上放置前导零。

【讨论】:

    【解决方案2】:

    整数(和浮点数)不能用前导零写入。在这种情况下,您可以将它们转换为这样的字符串:

    new_time = [10,5]
    ls= [f'{_:02}' for _ in new_time]
    print(ls) # Returns ['10', '05']
    

    【讨论】:

      【解决方案3】:

      恐怕你不能为int类型的值显示左零,除非你把它们改成str

      new_time = ["%02d"%i for i in new_time]
      

      为此,new_time 输出:

      ['10', '05']
      

      【讨论】:

        【解决方案4】:
          new_time = [10, 5]
          formated_time = []
          for item in new_time:
          if item < 10:
             time = f"0{item}"
             formated_time.append(time)
          if item >= 10:
             time = item
             formated_time.append(time)
          print(formated_time)
          """note:but while using it again you should use type('int') before the item"""
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 2023-01-18
        • 2019-05-08
        • 1970-01-01
        • 2021-10-29
        • 2019-07-19
        • 2021-12-30
        • 2015-07-03
        • 1970-01-01
        相关资源
        最近更新 更多