Create list from string

Chris cwitts at gmail.com
Fri Jun 13 10:29:15 EDT 2008


On Jun 13, 4:15 pm, ericdaniel <eric.acev... at gmail.com> wrote:
> Hi,
>
> I'm new to Python and I need to do the following:
>
> from this:   s = "978654321"
> to this :      ["978", "654", "321"]
>
> Any help is appreciated
>
> Thanks,
>
> Eric

What you could do is iterate over the string appending the characters
1 at a time to a new string and when you hit the point you want to
place it in your output list you can append it there and clear the
temp string eg.

length = 3
tmp_string = ''
results = []
for i,character in enumerate(s):
    if not (i+1) % length:
        results.append(tmp_string)
    else:
        tmp_string += character

I don't like this approach as you create to many temp items and fairly
ugly.
What you could do is to rather use slicing to build it.

results = []
length = 3
for i in xrange(0,len(s),length):
    results.append(s[i:i+length])

And then the neatest approach would be to put that into a list
comprehension instead

s = "978654321"
step = 3
output = [s[start:start+step] for start in xrange(0,len(s),step)]

Those are just some ways to do it.
Hope that helps



More information about the Python-list mailing list