如何对读取为字符串的数字进行操作
How to operate with numbers read as strings
通过readline()
我读了一个包含字母和数字的txt文件。
txt文件第一行是 18 20 8.9354 0 0
,我是这样读的
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]
问题是所有的数字都是字符串,如果我尝试做 A+B
我得到 1820
而不是 40
如何在本地修复它(仅针对实际包含数字的行)?
非常感谢
我会在这里使用字符串拆分和列表理解将每个字符串编号映射到真正的浮点数:
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]
通过readline()
我读了一个包含字母和数字的txt文件。
txt文件第一行是 18 20 8.9354 0 0
,我是这样读的
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]
问题是所有的数字都是字符串,如果我尝试做 A+B
我得到 1820
而不是 40
如何在本地修复它(仅针对实际包含数字的行)? 非常感谢
我会在这里使用字符串拆分和列表理解将每个字符串编号映射到真正的浮点数:
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]