split() 通过指定分隔符对字符串进行切片,分隔符默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
示例:
str = 'xiaoming 99 98 100' cols = str.split() print(cols[0]) print(cols[1]) print(cols[2])
str = 'xiaoming 99 98 100' cols = str.split() name = cols[0] sum = float(cols[1])+float(cols[2])+float(cols[3]) print(name, sum)
首先创建txt文件,输入以下内容并保存
xiaoming 99.5 100 99 xiaohong 60 70 80 xiaogang 78 88 98 xiaoqiang 34 44 54 xiaofeng 29 29 29
我们这里假设第一个数字是语文的分数,第二个数字是数学的分数,第三个数字是英语的分数
import tkinter import tkinter.filedialog fn = tkinter.filedialog.askopenfilename(filetypes=[('TXT', '.txt')]) print(fn) with open(fn) as f: lines = f.readlines() print(lines) sum = 0 for l in lines: print(l)
import tkinter import tkinter.filedialog fn = tkinter.filedialog.askopenfilename(filetypes=[('TXT', '.txt')]) print(fn) with open(fn) as f: lines = f.readlines() print(lines) sum = 0 for l in lines: cols = l.split() name = cols[0] sum = float(cols[1])+float(cols[2])+float(cols[3]) print(name, sum)