Search code examples
pythonpython-3.xprintingreadlinereadlines

f.readlines(): how to print without extra figures


I am trying to print from f.readlines. As seen in the code, when I print a, it prints each element in a new line without any extra additions (\,n,"). However when I try to split the string and call only a specific element, it adds the extra symbols. How do I fix this?

cargo.txt
wardrobe 550.30
mattress 300.10
fauteuil 600.00
drawer 1230.55
hammock 75.00

code:

import sys
fn = sys.argv [1]
wl= sys.argv [2]
with open ("cargo.txt","r") as f:
    a = (f.readlines())
    print(*a)
    b = a.split()
    print(b[1])

Solution

  • Here is how you can extract all the floats:

    with open ("cargo.txt","r") as f:
        a = [l.split()[1] for l in f.readlines()]
        print(a)
    

    Output:

    ['550.30', '300.10', '600.00', '1230.55', '75.00']