简体   繁体   中英

Python printing list of items

Below is my function and output. I want to remove the \n present in the output.

def printInventory():

    fh = open("stock.txt","r")

    print('Current Inventory')
    print('-----------------')

    L=fh.readlines()
    print("List of all Stock Items")
    for i in L:
        L=i.split(",")
    print(L)

    CHOICE = int(input('Enter 98 to continue or 99 to exit: '))
    if CHOICE == 98: 
        menuDisplay() 
    else: 
        exit()

Output:

List of all Stock Items ['APPLE', '100\n'] ['BANANA', '50\n'] ['CHILLI', '100\n'] ['MANGO', '300\n'] 

I would like to remove the \n from the output

You can use the.strip() function to remove the new line character

For instance:

out = ['APPLE', '100\n']
out[1] = out[1].strip('\n')
print(out) # ['APPLE', '100']

If you have a list of values, you can just loop through and apply the same logic to each item in the list

Since you are reading each line, you could rewrite the code to iterate over each line once instead of reading them all at once with readlines() . This has the benefit of not modifying the list you are iterating over.

def printInventory():
    L = []

    print('Current Inventory')
    print('-----------------')

    with open("stock.txt", "r") as fh:
        for line in fh:
            line = line.strip()
            L.append(line.split(","))
    print(L)
    # ...

Using the with open() syntax also ensures that the file is closed properly, even if the program crashes: Why is `with open()` better for opening files in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM