[Tutor] elegant way to turn list into string?

Alan Gauld alan.gauld at freenet.co.uk
Sat May 7 13:00:57 CEST 2005


> alph =

["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","
r","s","t","u","v","w","x","y","z"]

import string
alph = string.lowercase

> print "\n"
> print alph
> print "\n"

print '\n%s\n' % alph

> x = 1
> while x < 26:

for letter in alph:

>     alph.append(alph.pop(0))
>     print alph
>     print "\n"

Or:

first = alph[0]
alph = alph[1:] + first

Or more generically:

def rotate(seq, n):
    first = seq[:n]
    return seq{n:] + first

result = rotate(string.lowercase, 1)

> anyway- I don't like the output which come in the
> form:
> ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
> 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
> 'w', 'x', 'y', 'z', 'a']
>
>
> What I'd like to do is take my list and turn it into a
> string, which looks neater when printed.

Or start with a string in the first place?
But if you must use a list then

''.join(alph)

should work.

> I've tried using join() but that didn't work, can
> anyone give me a pointer here?

What happened? Did you remember to use the empty string as
the joining string?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list