-1

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

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Ash
  • 5
  • 3
  • Does this answer your question? [Getting rid of \n when using .readlines()](https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines) – Pranav Hosangadi Nov 23 '22 at 04:47

2 Answers2

0

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

atlas
  • 11
  • 1
0

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?

Dash
  • 1,191
  • 7
  • 19