faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 9 people (89%) answered Yes
Recently 8 of 9 people (89%) answered Yes

Entry

How do i join a list of numbers? (ie print out a=range(1,5) as 1:2:3:4:5

May 30th, 2002 06:19
Michael Chermside, Robby Stephenson, nathanial mayweather,


The way to join a list of *strings* is with the join() method of String
objects:
>>> a = ['three', 'words', 'long']
>>> '_'.join( a )
'three_words_long'
But this won't work on a list of numbers:
>>> a = range(1,5)
>>> ':'.join( a )
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in ?
    ':'.join( a )
TypeError: sequence item 0: expected string, int found
So first you have to convert the numbers to strings. The easiest way is
probably to call str() on each one in turn:
>>> a = range(1,5)
>>> ':'.join( [str(x) for x in a] )
'1:2:3:4'
Some people prefer the function map() to using a list comprehension:
>>> a = range(1,5)
>>> ':'.join( map(str, a) )
'1:2:3:4'
... but you're welcome to use whichever is easier for you.