Joining a list of strings, or ints
Published: Wednesday, Dec 26, 2007 Last modified: Thursday, Nov 14, 2024
I think the join syntax is slightly strange:
>>> list = ['cow','dog','cat']
>>> print list.join()
Traceback (most recent call last):
File “
AttributeError: 'list' object has no attribute 'join'
>>> print join.list()
Traceback (most recent call last):
File “
NameError: name 'join' is not defined
>>> print ''.join.list
Traceback (most recent call last):
File “
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 “
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