Search code examples
pythonpython-3.xstringfloating

How to operate with numbers read as strings


Via readline() I read a txt file which includes both letters and numbers. In the txt file the first line is 18 20 8.9354 0 0 and I read it in this way

import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
f = open(file_path)
with open(file_path) as fp:
    first_line = fp.readline()
    A = first_line[1:3]
    B = first_line[4:6]
    C = first_line[7:13]
    D = first_line[14]

The problem is that all the numbers are strings and if I try to do A+B I get 1820instead of 40

How can I fix it locally (Only for the lines that actually include numbers)? Many thanks


Solution

  • I would use string split here along with a list comprehension to map each string number to a bona fide float:

    with open(file_path) as fp:
        first_line = fp.readline()
        nums = first_line.split(' ')
        results = [float(i) for i in nums]
        A = results[0]
        B = results[1]
        C = results[2]
        D = results[3]