Python Forum

Full Version: If an element of a 'Split' is empty
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm 'splitting' a string and if an 'empty element found I'm trying replacing it with an "EMPTY ELEMENT"
Code:
import os
l_f = 'ELEMET-0,ELEMET-1'
sp_l_fapp = l_f.split(",")             

if  sp_l_fapp[2] :
    sp_l_fapp[2]=sp_l_fapp[2].strip()
    print (" SPLITED--->>> ",sp_l_fapp[2])
else : 
    sp_l_fapp[2] = 'EMPTY ELEMENT'
    print (" Priduct Line is empty ! ! ! -->> ",sp_l_fapp[2])
But still getting an error:
if sp_l_fapp[2] :
IndexError: list index out of range
If you print sp_l_fapp you'll see that it only has two elements. In python that's zero and one. There is no sp_l_fapp [2]

l_f = 'ELEMET-0,ELEMET-1'
sp_l_fapp = l_f.split(",")             
print (sp_l_fapp)
thank you, I know that.
The string actually has 3 elements but sometimes it could be 2 (no third element)
I want to test if the element [2] has a value:
if  sp_l_fapp[2] :
    sp_l_fapp[2]=sp_l_fapp[2].strip()
    print (" SPLITED--->>> ",sp_l_fapp[2])
And if not then replace an empty value:

else : 
    sp_l_fapp[2] = 'EMPTY ELEMENT'
    print (" Priduct Line is empty ! ! ! -->> ",sp_l_fapp[2])
Then you'll need to use try/except to catch the error.

l_f = 'ELEMET-0,ELEMET-1'
sp_l_fapp = l_f.split(",")             
 
try :
	if  sp_l_fapp[2] :
		sp_l_fapp[2]=sp_l_fapp[2].strip()
		print (" SPLITED--->>> ",sp_l_fapp[2])
except IndexError :
    sp_l_fapp.append  ('EMPTY ELEMENT')
    print (" Product Line is empty ! ! ! -->> ",sp_l_fapp[2])
Sorry, I misunderstood.
or use len()
def pad(list_, len_, pad_=None):
    """Pad list_ to len_ using pad_"""
    return list_ + [pad_] * (len_ - len(list_))

print(pad('Now is the time'.split(), 6))
Output:
['Now', 'is', 'the', 'time', None, None]
May be useful to have in your toolbox.
Thank you!
Try with 'append' looks amazing... Big Grin
I somehow missed append.... Confused

The function is confusing for now.
Must read about 'pad'.

Thank you again!
pad is just the name I gave to the function. It is a commonly used name for things that fill something out to a specified size. Just add some padding.