Python Forum

Full Version: Testing Split elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I'm looking for a line that has multiple spaces and the word "Motherboard:" at the beginning of the line.
If it found I would split the line and get the fourth element, which is a Serial number.
I'm trying to test splitted elements and if an element [4]==0 write something else instead.
I was sure it will work but it does not. I got this error "IndexError: list index out of range"

if '    Motherboard:' in rn_l :
	mb=re.split(r" {2,}", rn_l)
	if not mb[4] :
	   mb[4] ="No Serial Num"
	else :
		print (f" Motherboard Serial number   -->> {mb[4]}")      
Line 2 will split and give you back a list. But you are not guaranteed for that list to be any particular length. If the list has less than 5 elements, then referring to mb[4] (as done on line 3) will be an error.
what about
line = line.strip()
if line.strip().startswith('Motherboard:'):
    try:
        print (f"Motherboard Serial number   -->> {line.split()[4]}")
    except IndexError:
       print("No Serial Num")
I do not have a problem splitting.
I need to replace the fourth element in a split if the element does not exist.
Here is a line to split:
   Motherboard:   Ao11   Build-211   DT 2021 SN-0123A456
if the line has nothing after the word "Motherboard:"
   Motherboard:  
I want to print something like "not there" or "empty" or "No Serial Num"
I thought I could split the line and test elements if they are ==0 or not.
That is why I'm testing element 4 if it is empty.

    mb=re.split(r" {2,}", rn_l)
    if not mb[4] :
       mb[4] ="No Serial Num"
    else :
        print (f" Motherboard Serial number   -->> {mb[4]}")
(May-08-2021, 09:56 PM)tester_V Wrote: [ -> ]That is why I'm testing element 4 if it is empty.
Yes,but you can not do like this as mb[4] will give IndexError when empty.
Then you need to do as buran show,so for you code it would be like this.
import re

rn_l = 'Motherboard:   Ao11   Build-211   DT 2021 SN-0123A456'
#rn_l = 'Motherboard:'
mb = re.split(r" {2,}", rn_l)
try:
    print (f"Motherboard Serial number -->> {mb[3]}")
except IndexError:
    print("No Serial Num")
Output:
Motherboard Serial number -->> DT 2021 SN-0123A456 # Test empty No Serial Num