Search code examples
python-3.xlisterror-handlingsplittry-except

Check for an empty variable when using split() in python3


If I have for example a line of string like this:

line = alfa,bravo,zeta,cookie,dragonball

I can create them into a list like this:

parts = line.split(",")

However, I should be able to deal with an error if the line has "empty" objects, like in the following situations:

,coookie,dragonball,alfa
alfa,,dragonball,cookie
alfa,dragonball,cookie,

How can I do this? in case of an error, the line would not be included in a list, and the program would give an error message:

print("ERROR in line: {}".format(line))

I thought about using a try/except, but I don't really know how it should be formatted in this case.


Solution

  • Try this:

    line = "alfa,bravo,zeta,cookie,dragonball"
    
    if "" in line.split(","):
    
        print("ERROR in line: {}".format(line))
        ## further error handling...