首页 > 解决方案 > 如何将空字符串转换为“无”(python 3 使用 thonny)

问题描述

我试图编写一个程序来打开和读取文件并将文件中的数字转换为整数。但是文件中有空字符串,我只是不知道如何将空字符串转换为“无”。我这样做是为了在我稍后尝试将它们转换为整数时绕过“ValueError:int() 的无效文字,基数为 10”。

在 Thonny 上使用 Python 3,编程新手

def get_student(studentfile):

with open(studentfile, 'r') as students: #opens file as students
        for aline in students:  

            values = aline.split(",") #breaks up line into strings

            student_names, student_marks = values[:1], values[1:13] #  assigning variables to stings

            for digits in student_marks: ###THIS IS WHERE I HIT A WALL
                if [digits] is None:    ### i tried to turn empty     strings into NONE 
                    [digits] = "None"
                else:
                    return [digits]

            student_marks = list(map(int, student_marks[1:])) #converts number strings into integer

            print( student_names , end="") # combine into a list
            print( [student_marks]) 
            info = students.read()
            students.close
            print( info ) #print list

标签: python

解决方案


你为什么要把它变成None? 只需忽略它,或者您也可以先用新行拆分,然后用逗号拆分,我认为这样您就不会有空字符串。


推荐阅读