如何移除Python库存打印输出中的\n换行符?
解决库存数量中的换行符问题
问题描述
编写了printInventory()函数读取stock.txt文件并打印库存信息,但输出的库存数量后带有\n换行符,示例输出:
List of all Stock Items ['APPLE', '100\n'] ['BANANA', '50\n'] ['CHILLI', '100\n'] ['MANGO', '300\n']
需要移除这些多余的换行符。
解决方案
你可以在读取文件内容时,用字符串的strip()或rstrip()方法去除换行符,以下是两种常用实现方式:
方法1:用strip()清除首尾空白字符(含换行符)
如果不需要保留数量前后的任何空白字符,直接用strip()一次性清除:
def printInventory(): stock_list = [] with open('stock.txt', 'r') as f: for line in f: # 假设每行格式为 "商品名,数量" item, quantity = line.strip().split(',') stock_list.append([item, quantity]) print("List of all Stock Items", ' '.join(map(str, stock_list)))
方法2:用rstrip('\n')仅清除末尾换行符
如果需要保留数量前后的其他空白字符,可针对性只去掉换行符:
def printInventory(): stock_list = [] with open('stock.txt', 'r') as f: for line in f: item, quantity = line.rstrip('\n').split(',') stock_list.append([item, quantity]) print("List of all Stock Items", ' '.join(map(str, stock_list)))
效果说明
修改后输出示例:
List of all Stock Items ['APPLE', '100'] ['BANANA', '50'] ['CHILLI', '100'] ['MANGO', '300']
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

