5
votes

How do I convert a list of ints to a single string, such that:

[1, 2, 3, 4] becomes '1234'
[10, 11, 12, 13] becomes '10111213'

... etc...

2

2 Answers

20
votes
''.join(map(str, [1,2,3,4] ))
  • map(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1', '2', '3', '4'].
  • s.join(a) concatenates all items in the sequence a by the string s, for example,

    >>> ','.join(['foo', 'bar', '', 'baz'])
    'foo,bar,,baz'
    

    Note that .join can only join string sequences. It won't call str automatically.

    >>> ''.join([1,2,3,4])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sequence item 0: expected string, int found
    

    Therefore we need to first map all items into strings first.

12
votes
''.join(str(i) for i in [1,2,3,4])