[Tutor] parsing woes
Don Arnold
darnold02 at sprynet.com
Fri Aug 22 23:16:50 EDT 2003
----- Original Message -----
From: "Vicki Stanfield" <vicki at thepenguin.org>
To: <tutor at python.org>
Sent: Friday, August 22, 2003 10:46 AM
Subject: [Tutor] parsing woes
> 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
>
How about using len( ) to test for the number of parameters you're dealing
with? Not too pretty, but:
def parse(arguments=''):
parameters = arguments.split()
numParams = len(parameters)
if numParams > 0:
print parameters[0]
if numParams > 1:
print parameters[1]
if numParams > 2:
print parameters[2]
so:
>>> parse('1 2 3')
1
2
3
>>> parse('1 2')
1
2
>>> parse('1')
1
>>> parse('')
Note that the last one prints nothing since an empty string was passed.
HTH,
Don
More information about the Tutor
mailing list