简体   繁体   中英

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 1820 instead of 40

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

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]

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