我有这个格式,我需要遵守其他打印号码列表(该列表有200多个号码):
my_format = '%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d\n'
my_list = [1,2,3,4,5,6,199, 57, .........]
基本上,它只是%6d重复15次
使用%格式化字符串时,我知道需要执行以下操作:
with open('my_out.txt', 'w') as fout:
fout.write(my_format % (num1, num2, num3, num4, num5, ....., num15)
在我的情况下,我需要将我的_列表分成15个部分,在最后一个部分中,我可能没有15个数字;因此,我需要以某种方式忽略变量num,因为我已经遍历了所有的数字,所以它在我的_列表中没有任何项。另外,考虑到我需要创建15个变量(从num1到num15),因此我可以使用:
my_format % (num1, num2, num3, num4, num5, ....., num15)
我的文件应如下所示:
0112345678911121
145897589765430
346718
有没有一种聪明有效的方法可以解决我的问题
只需使用
%6d
格式化各个项目,然后在空字符串上连接它们,并在末尾添加换行符:这不是一种聪明的(甚至是Python式的)方式,但它可以完成任务:
您可以将其作为列表或直接打印到文件中
该解决方案由@Aplet123提供。我只是把所有的东西放在一起
相关问题 更多 >
编程相关推荐