-2

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

  • Do you not know about using `float()` and `int()` to convert strings to numbers? Or are you asking how you can detect if a string contains a number before you convert it? It'd be helpful if you included info on why you need help and what you've tried or know about. – Random Davis Oct 06 '20 at 16:29
  • 1
    Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – Pranav Hosangadi Oct 06 '20 at 16:51

1 Answers1

1

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]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • If you wanted, you could also write the last four assignments more concisely with [sequence unpacking](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) as `A, B, C, D = results[0:4]`. – betaveros Oct 06 '20 at 16:59