[Tutor] parsing woes
Scott Widney
SWidney at ci.las-vegas.nv.us
Mon Aug 25 15:22:46 EDT 2003
> 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.
.
.
.
> 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.
Maybe I'm missing something, but why not use a for loop to iterate through
the parameters (if any)? And
#####
>>> args1 = "1 F 5"
>>> args2 = "2 G"
>>> args3 = "3"
>>> args4 = ""
>>> def parse_and_print(parameters=""):
... for param in parameters.split(): print param
...
>>> parse_and_print(args1)
1
F
5
>>> parse_and_print(args2)
2
G
>>> parse_and_print(args3)
3
>>> parse_and_print(args4)
>>> parse_and_print()
>>> parse_and_print("")
>>> parse_and_print("1 F 5 2 G 3")
1
F
5
2
G
3
>>>
#####
There are safety precautions one could take, but if you're sure the argument
is always going to be a string then this should suffice.
Scott
More information about the Tutor
mailing list