[Tutor] parsing woes
Clay Shirky
clay at shirky.com
Sat Aug 23 13:21:38 EDT 2003
> 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.
The function len() will tell you the length of the list you are making, so
rather than testing each value, you can just test the total length to see
how many parameters there are.
You can see this in action here:
argument_list = ["1 F 5",
"2 G H 6",
"3 IJ KL MN 7",
"4"]
for arguments in argument_list:
parameters=arguments.split() # split splits on space by default
print len(parameters),
This prints "3 4 5 1", the number of parameters in each of those four test
samples.
Now you can loop...
for i in range( len(parameters) ):
print parameters[i]
Or test...
if len(parameters) > 2:
print parameters[2]
-clay
More information about the Tutor
mailing list