Convert mixed list to string

Viewed 774

I have the list below, which contains strings and integers. How do I make a string of them? Tried to use

''.join(l)

but it does't work, because there are integers on the list(specifically, L[1] is an integer, and the others are all strings.). Can you help?

L=['1', 9, ':', '0', '5', ':', '4', '5']
#expected "19:05:45"
4 Answers

You can convert each number in the list into a string with a for loop or list comprehension. Like so:

l = ['1', 9, ':', '0', '5', ':', '4', '5']

''.join([str(x) for x in l])

'19:05:45'

Generators are perfect in this case:

>>> l = ['1', 9, ':', '0', '5', ':', '4', '5']
>>> ''.join(str(x) for x in l)
'19:05:45'

This looks the same as a list comprehension but does not require the creation of another list instance.

Just map all the elements to string before joining.

>>> ''.join(map(str,['1', 9, ':', '0', '5', ':', '4', '5']))
'19:05:45'

You can do it in a for loop

list_str = ''
for i in l:
    list_str += str(i)

Or a with a list comprehension

list_str = ''.join([str(i) for i in l])
Related