如何在python中逐个复制输入文件ch并使用格式?
我一直在尝试一个字符一个字符地复制输入文件,然后尝试格式化它们,以避免任何类型的对齐问题。输入文件中的第一项长度为50个字符,第二项长度为6个字符,第三项长度为3个字符,第四项长度为25个字符,第五项长度为4个字符。我不允许使用列表或元组。以下是我的代码:如何在python中逐个复制输入文件ch并使用格式?,python,Python,我一直在尝试一个字符一个字符地复制输入文件,然后尝试格式化它们,以避免任何类型的对齐问题。输入文件中的第一项长度为50个字符,第二项长度为6个字符,第三项长度为3个字符,第四项长度为25个字符,第五项长度为4个字符。我不允许使用列表或元组。以下是我的代码: input_file=open('measles.txt','r') f1=input('file name: ') output_file=open(f1,'w') for line in input_file: newstri
input_file=open('measles.txt','r')
f1=input('file name: ')
output_file=open(f1,'w')
for line in input_file:
newstring=''
line=line.strip()
for ch in line:
#I am trying to format the first two items in the input file
print('{0:50}{51:57}'.format(line[0:50],line[51:57]),file=output_file)
input_file.close()
output_file.close()
我得到的错误如下:
Traceback (most recent call last):
File "C:/Users/Dasinator/Documents/Books IX/Python Examples/proj07.py", line 10, in <module>
print('{0:50}{1:57}'.format(line[0:50],line[51:57]),file=output_file)
IndexError: tuple index out of range
输出看起来仍然没有完全对齐
这就是我修改代码的方式,但仍然有一些问题
print('{0:50s}{1:6s}{2:<3s}{3:<25s}{4:<4s}'.format(line[0:50],line[50:56]),line[56:59],line[59:84],line[84:87],file=output_file)
print({0:50s}{1:6s}{2:Why 51在第二个参数中:{0:50}{51:57}
?,应该是1
:
print('{0:50}{1:57}'.format(line[0:50],line[51:57]),file=output_file)
# ^^^
作为测试:
>>> print('{0:10}{57:10}'.format(10,20))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> print('{0:10}{1:10}'.format(10,20))
10 20
打印({0:10}{57:10})。格式(10,20))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器错误:元组索引超出范围
>>>打印({0:10}{1:10})。格式(10,20))
10 20
若要将第二列与左侧对齐,请使用
看起来您误解了.format的工作原理以及格式化字符串的外观
编写字符串“{0:50}{1:50}”时,格式(stuff0,stuff1)
冒号将索引(之前)与字符串在打印时应使用的字符数分开
因此,当您这样做时:
print({0:50}{51:57})。格式(第[0:50]行,第[51:57]行),file=output_file)
您告诉python使用.format的第51个参数。您实际的意思是.format的第二个参数,或者字符串中的第51个字符
大概,您在这里实际要做的是打印该行的第0-50个字符,以及第51-57个字符。这将如下所示:
print({0:10}{1:10})。格式(第[0:50]行,第[51:57]行),file=output\u file)
此外,我不知道file参数的作用是什么,但它可能不会达到您预期的效果。请显示输入文件的内容。对不起,我注意到了这个错误并修复了它。但是,您能否根据我在原始que中给出的字符长度,为输出文件中的所有项目提供代码stion。再次感谢。抱歉,注意到该错误并修复了它以生成新的输出,但它看起来仍然没有完全对齐。“完全对齐”是什么意思?如果要不同的对齐方式,请更改冒号后面的数字,即如果第一列中要有50个字符,第二列中要有6个字符,请使用“{0:50}{1:6}”。如果要在列之间填充,请适当增加冒号右侧的两个数字。
print('{0:50}{1:57}'.format(line[0:50],line[51:57]),file=output_file)
# ^^^
>>> print('{0:10}{57:10}'.format(10,20))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> print('{0:10}{1:10}'.format(10,20))
10 20
print('{0:50}{1:<57}'.format(line[0:50],line[51:57]),file=output_file)