如何使用python将[1,2,3,4]更改为"1234" [英] how to change [1,2,3,4] to '1234' using python

查看:931
本文介绍了如何使用python将[1,2,3,4]更改为"1234"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将int的列表转换为单个字符串,例如:

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

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

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

...等等...

推荐答案

''.join(map(str, [1,2,3,4] ))

  • map(str, array) 等同于[str(x) for x in array],因此map(str, [1,2,3,4])返回['1', '2', '3', '4'].
  • s.join(a) 连接序列中的所有项目a,例如字符串s

    • 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'
      

      请注意,.join只能连接字符串序列.它不会自动调用str.

      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
      

      因此,我们需要先map将所有项目首先放入字符串中.

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

      这篇关于如何使用python将[1,2,3,4]更改为"1234"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆