Joining a list of strings, or ints

Published: Wednesday, Dec 26, 2007 Last modified: Saturday, Mar 23, 2024

I think the join syntax is slightly strange:

>>> list = ['cow','dog','cat']

>>> print list.join()

Traceback (most recent call last):

File “”, line 1, in ?

AttributeError: 'list' object has no attribute 'join'

>>> print join.list()

Traceback (most recent call last):

File “”, line 1, in ?

NameError: name 'join' is not defined

>>> print ''.join.list

Traceback (most recent call last):

File “”, line 1, in ?

AttributeError: 'builtin_function_or_method' object has no attribute  'list'

>>> print ''.join(list)

cowdogcat

>>> print ' '.join(list)

cow dog cat

>>>

Ok if you try join a list of ints:

>>> ' '.join([12,34,56,78])

Traceback (most recent call last):

File “”, line 1, in ?

TypeError: sequence item 0: expected string, int found

It will not work. What you need is to convert each int into a str. Nasty, I know :

>>> ' '.join(map(str,([12,34,56,78])))

'12 34 56 78'

Thanks to #python, in partic. dash