简体   繁体   English

2个地方的列表的格式化元素问题

[英]Issue with formating element of list on 2 places

I'm trying to format my data on 2 places.我正在尝试在 2 个地方格式化我的数据。 If it contains only 1 element, it should append 0 to it.如果它只包含 1 个元素,它应该 append 0 到它。 For example new_time = [10,52] My desire output is [10,52 ] For [10,5] My desire output is [10,05] I read about this method new_time = [new_time[0],new_time[1]:02] .例如new_time = [10,52]我的愿望 output 是 [10,52 ]对于 [10,5] 我的愿望 output 是 [10,05] 我读过这个方法new_time = [new_time[0],new_time[1]:02] But output of this is invalid syntax.但是 output 是无效的语法。 Does anybody know why it isn't work?有谁知道为什么它不起作用? I did similar exercise and it works.我做了类似的练习,效果很好。

It is not possible for integers to be denoted with leading zeroes, and it is by design.整数不可能用前导零表示,这是设计使然。 Try to run this statement into your python console: print(05) .尝试在您的 python 控制台中运行此语句: print(05) You would get an error stating that您会收到一条错误消息,指出

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

But you can typecast integers into strings and logically put leading zeroes if you need.但是如果需要,您可以将整数类型转换为字符串并在逻辑上放置前导零。

Integers(and Floats) can not be written with leading zeros.整数(和浮点数)不能用前导零写入。 What you can do in this case is to convert them to string like this:在这种情况下,您可以将它们转换为字符串,如下所示:

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

I'm afraid you can not display left-zeros for values of type int , unless you change them into str :恐怕您不能为int类型的值显示左零,除非您将它们更改为str

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

for which, new_time outputs:为此, new_time输出:

['10', '05']
  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"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM