How can I add zero's in empty slots in a list in python?
for example
list_1 = ['2','4',' ','3',' ','1',' ']
output I want:
['2','4','0','3','0','1','0']
CodePudding user response:
Here is a list comprehension that will do it:
list_1 = ['0' if i.strip() == '' else i for i in list_1]
CodePudding user response:
Try this:
list_1 = ['2','4',' ','3',' ','1',' ']
list_1 = ['0' if l.isspace() or not l else l for l in list_1]
print(list_1)
Output:
['2', '4', '0', '3', '0', '1', '0']
CodePudding user response:
You can also do it like this
list_1 = ['2','4','','3','','1','']
for i in list_1:
if i =="":
list_1[list_1.index(i)] = 0
print(list_1)