[Tutor] Re: parsing woes
Vicki Stanfield
vicki at thepenguin.org
Fri Aug 22 14:18:57 EDT 2003
> Okay, I didn't get an answer to this last time, so let me restate it and
> try again. I am attempting to parse a string which is in the form:
>
> 1 F 5
>
> I need to make parameter[0]= 1, parameter[1] = F, and parameter[2] = 5.
> The difficulty is that there might be no parameters or any number up to 3.
> They won't always be a single digit or letter but they will always be
> space-delimited. My problem is that when I try to display them, I get an
> error if there are not 3 parameters.
>
> if parameters[2]:
> IndexError: list index out of range
>
> when I try to run this code to see what the values are:
> if parameters[0]:
> print parameters[0]
> if parameters[1]:
> print parameters[1]
> if parameters[2]:
> print parameters[2]
>
> I am parsing them this way:
>
> if arguments:
> parameters=arguments.split(" ")
> else: parameters = ""
>
>
> Can someone tell me what I am doing wrong? I just want the if
> parameters[2] to be bypassed if there isn't a third parameter.
>
> --vicki
>
>
Okay I finally got it figured out. I had to change the if statements to
try statements and deal with the index error. The code looks like this
now:
if arguments:
parameters=arguments.split(" ")
i=0
for a in parameters:
print "parameter[" + str(i) + "] = " + a + "\n"
i+=1
and then:
try:
parameters[0]
except IndexError:
print "parameters[0] undefined"
else:
print parameters[0]
try:
parameters[1]
except IndexError:
print "parameters[1] undefined"
else:
print parameters[1]
try:
parameters[2]
except IndexError:
print "parameters[2] undefined"
else:
print parameters[2]
--vicki
More information about the Tutor
mailing list