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

后端 未结 2 482
借酒劲吻你
借酒劲吻你 2020-12-19 13:12

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

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

相关标签:
2条回答
  • 2020-12-19 13:38
    ''.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.

    0 讨论(0)
  • 2020-12-19 14:03
    ''.join(str(i) for i in [1,2,3,4])
    
    0 讨论(0)
提交回复
热议问题