如何让Python购物清单程序在终端与文件中逐行打印条目?
解决购物清单条目逐行显示的问题
你的代码当前的问题是:所有购物条目被直接拼接成无换行的字符串,导致写入文件和终端输出时内容挤在一起,没有逐行显示。下面提供两种可行的修改方案:
方案1:直接在每个条目后添加换行符
修改输入累加的逻辑,每次获取用户输入后追加换行符,确保每个条目之间有换行分隔:
#By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights reserved. By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights reserved. items = input('What is the first item on your shopping list:\n') + '\n' items += input('What is the second item on your shopping list:\n') + '\n' items += input('What is the third item on your shopping list:\n') + '\n' items += input('What is the fourth item on your shopping list:\n') + '\n' items += input('What is the fith item on your shopping list:\n') + '\n' items += input('What is the sixth item on your shopping list:\n') + '\n' items += input('What is the seventh item on your shopping list:\n') + '\n' items += input('What is the eighth item on your shopping list:\n') + '\n' items += input('What is the ninth item on your shopping list:\n') + '\n' items += input('What is the tenth item on your shopping list:\n') + '\n' shopping_list = 'shopping list:' file = open('shopping_list.txt', 'w') file.write(items) file.close() file = open('shopping_list.txt', 'r') for line in file: print(line) # print默认自带换行,end='\n'可省略 file.close()
方案2:用列表存储条目(更简洁高效)
重复编写10次输入代码冗余度高,用循环收集条目后再用换行符拼接,代码更简洁易维护:
#By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights reserved. By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights reserved. items = [] # 循环收集10个购物条目,自动处理序数词(1st/2nd/3rd/th) for i in range(1, 11): suffix = "st" if i == 1 else "nd" if i == 2 else "rd" if i == 3 else "th" item = input(f'What is the {i}{suffix} item on your shopping list:\n') items.append(item) # 用换行符连接所有条目,生成带换行的字符串 items_str = '\n'.join(items) + '\n' # 末尾加换行保证文件结尾有空白行(可选) file = open('shopping_list.txt', 'w') file.write(items_str) file.close() file = open('shopping_list.txt', 'r') for line in file: print(line.strip('\n')) # 避免重复换行(文件行自带换行,print默认再添加一次) file.close()
两种方案都能实现:每个购物条目在文本文件和终端输出中逐行显示的效果。
内容的提问来源于stack exchange,提问作者Simeon Beckford-Tongs
相关产品推荐
相关产品推荐

