引入一个格式如下的文本文件:
hammer#9.95
saw#20.15
shovel#35.40我需要将其引入python,并对其进行格式化,以使其与现有的代码片段保持一致:
# display header line for items list print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )
目标是让文本文件与现有的头文件保持一致,如下所示:
Item Cost
hammer $9.95
saw $20.15
shovel $35.4我可以将文本文件引入到Python中,并将#符号替换为$符号:
file = open('Invoice.txt', 'r')
file_contents = file.read()
new_file_contents = file_contents.replace('#', '$')这给出了下面的输出:
hammer$9.95
saw$20.15
shovel$35.40但是我在格式化方面遇到了麻烦。有什么建议吗?
发布于 2018-04-28 00:20:23
你可以这样做:
with open(file,'rt',encoding='utf-8') as infile:
for line in infile:
print("{:<6} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1]))唯一的问题是,如果你有一个比锤子更长的词,它看起来会很难看。我建议首先在列表中找到最大的单词,然后将其用作{:<6}的限制符。
https://stackoverflow.com/questions/50066325
复制相似问题