【问题标题】: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"""