Python Forum
If an element of a 'Split' is empty
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
If an element of a 'Split' is empty
#1
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
Reply
#2
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)
Reply
#3
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])
Reply
#4
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.
tester_V likes this post
Reply
#5
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.
tester_V likes this post
Reply
#6
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!
Reply
#7
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to locate element no such element gahhon 6 4,501 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Change single element in 2D list changes every 1D element AceScottie 9 12,083 Nov-13-2017, 07:05 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020