*-unpacking (Re: Fun with fancy slicing)
David C. Fox
davidcfox at post.harvard.edu
Fri Oct 3 00:49:45 EDT 2003
Greg Ewing (using news.cis.dfn.de) wrote:
> Alex Martelli wrote:
>
>> How sweet it would be to be able to unpack by coding:
>> head, *tail = alist
>
>
> Indeed! I came across another use case for this
> recently, as well. I was trying to parse some
> command strings of the form
>
> command arg arg ...
>
> where some commands had args and some didn't.
> I wanted to split the command off the front
> and keep the args for later processing once
> I'd decoded the command. My first attempt
> went something like
>
> command, args = cmdstring.split(" ", maxsplit = 1)
>
> but this fails when there are no arguments,
> because the returned list has only one element
> in that case.
>
> It would have been very nice to be able to
> simply say
>
> command, *args = cmdstring.split()
>
> and get the command as a string and a
> list of 0 or more argument strings.
>
> I really ought to write a PEP about this...
>
In the mean time, it isn't too hard to write a function which does this:
def first_rest(x):
return x[0], x[1:]
command, args = first_rest(cmdstring.split())
or, in one step
def chop_word(s):
return first_rest(s.split())
command, args = chop_word(cmdstring)
David
More information about the Python-list
mailing list