[Tutor] parsing woes

Jason Thompson jason at museunlimited.com
Sat Aug 23 12:38:28 EDT 2003


If I'm understanding your question properly, you simply need to determine the 
length of your parameters list. The following example works for any number of 
parameters. 

#!/usr/bin/python

parameters = ['1', 'F', '5']

if len(parameters) == 0			#if there aren't any parameters
	print "No parameters given"
else:
	length = len(parameters)
	top = length-1			#the 'top' index for parameters
	for p in parameters:
		print parameters[top] 	#print the highest index in list
		top = top-1			#reduce by one to print next lowest

Obviously I've simplified your example a great deal, but if I'm understanding 
your problem correctly, this should get you started. This way your program 
will never try to address any parameter that doesn't exist.
Best,
Jason

On August 22, 2003 11:46 am, Vicki Stanfield wrote:
> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list