gpt4 book ai didi

python - 如何在Python中逐个复制输入文件ch并使用格式?

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:40 25 4
gpt4 key购买 nike

我一直在尝试逐字符复制输入文件,然后尝试对其进行格式化以避免任何类型的对齐问题。输入文件中的第一项为 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:
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

有人可以指出代码中的错误并推荐修复方法吗?谢谢

Andorra                                           WB_HI                                             
Andorra WB_HI
Angola WB_LMI
Angola WB_LMI
Angola WB_LMI

输出看起来仍然不完全对齐。

这就是我修改代码的方法,但仍然遇到一些问题。

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)

我得到的输出是

Traceback (most recent call last):
File "C:/Users/Dasinator/Documents/Books IX/Python Examples/proj07.py", line 10, in <module>
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)
IndexError: tuple index out of range

最佳答案

看来您误解了 .format 的工作原理以及格式化字符串应该是什么样子。

当您编写字符串“{0:50}{1:50}”.format(stuff0, stuff1)时,冒号将索引(之前)与字符串所包含的字符数分隔开。打印时字符串应该占据。

所以,当你这样做时:

print('{0:50}{51:57}'.format(line[0:50],line[51:57]),file=output_file)

您告诉 python 使用 .format 的第 51 个参数。您实际上的意思是 .format 的第二个参数,或字符串中的第 51 个字符。

大概,您在这里实际想要做的是打印该行的第 0-50 个字符,以及第 51-57 个字符。这看起来像:

print('{0:10}{1:10}'.format(line[0:50],line[51:57]),file=output_file)

此外,我不知道你的文件参数要做什么,但它可能不会达到你的预期。

关于python - 如何在Python中逐个复制输入文件ch并使用格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21960586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com