for循环中的format语句

2024-09-28 17:07:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将文件中的元组打印为:

for row in s:
    # Loop over columns.
    for column in row:
        print(column, type(column), end=" ")
        of1.write("%s  " % column)
        #of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(row))
        of1.write("\n")
        print(end="\n")

所有元素都是来自print语句输出的str:

64.08K <class 'str'> 20.0 <class 'str'> 0.95 <class 'str'> 1.7796943385724604e-05 <class 'str'> 

代码运行良好,但同样明显,格式不好。我正在尝试使用格式语句 以获得更好的格式,如注释行中所示,但它给出了错误:

File "eos_res.py", line 54, in <module>
    of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(row))
IndexError: tuple index out of range

请帮忙。你知道吗


Tags: 文件informatfor格式column语句class
1条回答
网友
1楼 · 发布于 2024-09-28 17:07:34

您试图将整行作为一个值传递给格式化。用途:

of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(*row))

让Python将row的各个值传递给.format()。你知道吗

或者,使用从一个位置参数中提取单个索引的格式:

of1.write("{0[0]:<10}{0[1]:<8}{0[2]:<23}{0[3]:<20}\n".format(row))

相关问题 更多 >