[Tutor] Re: parsing woes

Lloyd Kvam pythontutor at venix.com
Sat Aug 23 13:46:44 EDT 2003


I think you really want to know how many parameters are present.
parm_count = len(parameters)
will give you that information.

I do not understand enough of what you are doing to suggest much
more detail.  Presumably you could wind up with code like:
if parm_count == 0:
	# handle no parms
elif parm_count == 1:
	# adjust for two missing parms
elif parm_count == 2:
	# adjust for one missing parm
elif parm_count == 3:
	# do what needs to be done
else:
	# error handling for too many

if you write functions for these cases you could possibly do this:
{ 0: no_parms_func,
   1: one_parm_func,
   2: two_parm_func,
   3: three_parm_func}.get(len(parameters), too_many_func)(parameters)

Use len(parameters) to choose the correct function from a dictionary.
Specify a function for the "else" case.
Call (invoke) the funtion passing it the parameter list.


One other suggestion.  Your earlier email showed:
 >if arguments:
 >     parameters=arguments.split(" ")
 > else: parameters = ""
else: parameters = []
would probably be better.  In that case, note that "".split() returns [].
You probably do NOT need the if arguments test.

Hope this helps.

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.
>>...
> 
> 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:
 > ...
> --vicki

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list