[Tutor] string.split() into a list

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Oct 19 01:13:34 CEST 2005



On Tue, 18 Oct 2005, Kent Johnson wrote:

> >    l = []
> >    a, l = string.split('|')
>
> How about
>  >>> s='1|2|3|4'
>  >>> l=s.split('|')
>  >>> a, l = l[0], l[1:]
>  >>> a
> '1'
>  >>> l
> ['2', '3', '4']
> ?


Hi Randy,


I think you're expecting Perl behavior.  The Perl idiom for partially
destructuring an array looks something like this:

### Perl ########################################################
my @rest;
my $firstElement;
($firstElement, @rest) = split(/:/, "hello:world:this:is:a:test");
#################################################################


But we don't have a direct analog to this in Python, since there's no real
distinction between "scalar" and "array" values in the Python language.
In your original code:

    l = []
    a, l = string.split('|')

assigning 'l' to an empty list has no effect: it doesn't freeze the type
of 'l' so that it can only be a list.  For example:

######
>>> thing = []
>>> thing = 42
>>> thing = "blah"
######

show that we can easily redirect the name 'thing' to different kinds of
values.  List values in Python aren't any more special than other things.
If you come from a Perl background, the non-existance of array-vs-scalar
context issues is something you might need to keep in mind.


The closest we can probably get is with Kent's example, where the 'rest'
are explicitely bundled together by using list slicing.  Would something
like this be fine for you?

### Python #######################################################
def splitFirstAndRest(delimiter, text):
    pieces = text.split(delimiter)
    return pieces[0], pieces[1:]

first, rest = splitFirstAndRest(':', "hello:world:this:is:a:test")
##################################################################


Best of wishes!



More information about the Tutor mailing list