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.