How to change [1,2,3,4] to '1234' using python

How to convert a list intto a single line, for example:

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

... etc.

+5
source share
2 answers
''.join(map(str, [1,2,3,4] ))
  • map(str, array)equivalent [str(x) for x in array], therefore map(str, [1,2,3,4])returns ['1', '2', '3', '4'].
  • s.join(a)combines all the elements in a sequence ausing a string s, for example,

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

    Please note that .joincan only join sequences of lines. It will not call strautomatically.

    >>> ''.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, first you need to first mapall the elements in a row.

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

All Articles