简体   繁体   中英

My nested list always adds an empty string

For some reason, it keeps adding an empty ' ' in the nested list.

This is how the results are printed out:

[['Sara', '37', '32', '47', ''], ['Johan', '44', '29', '34', ''], ['Kalle', '33', '34', '34', ''], ['Oskar', '23', '47', '45', '']]

I have tried what is in this article but it doesn't work. Not sure where the fault is. https://www.geeksforgeeks.org/python-remove-empty-strings-from-list-of-strings/

def results_from_file(file_name):
    file_exist()
    
    my_file = open(file_name, "r")
    data = my_file.read().split("\n")
    
    results = []
    
    for row in data:
        results.append(row.split(";"))
    
    return results

As Aplet123 said:

Your lines probably all end in ;

Try this to fix:

replace

data = my_file.read().split("\n")

to

data = my_file.read().replace(';\n','\n').split("\n")

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