[Tutor] parsing woes

David Rock david at graniteweb.com
Fri Aug 22 23:17:17 EDT 2003


* Vicki Stanfield <vicki at thepenguin.org> [2003-08-22 10:46]:
> 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.

put it into a try block. The problem is you are accessing an index that
doesn't exist. This raises the IndexError exception:

try:
	if parameters[0]:
	   print parameters[0]
	if parameters[1]:
	   print parameters[1]
	if parameters[2]:
	   print parameters[2]
except:
	pass

This example just throws it away if there is an error during this block
of code. This is by no means a clean example, but it demonstrates how to
use the try/except code.

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030822/39bd48d3/attachment.bin


More information about the Tutor mailing list