【问题标题】:List of ints to string到字符串的整数列表
【发布时间】:2014-10-05 13:02:19
【问题描述】:

我有一个整数列表:

(83, 105, 101, 109, 101, 110, 115)

我相信这是Siemens 的代码。

如何以 Python 方式将此列表转换为字符串?

我知道我可以使用 chr(x) 获取单个字符并将它们连接起来,但这似乎不是最好的方法。

【问题讨论】:

    标签: python string char int


    【解决方案1】:

    使用bytes(或str)和bytearray

    >>> bytes(bytearray((83, 105, 101, 109, 101, 110, 115)))
    'Siemens'
    

    在 Python 3.x 中:

    >>> bytes((83, 105, 101, 109, 101, 110, 115)).decode()
    'Siemens'
    

    【讨论】:

    • 我们实际上不需要bytes
    • @thefourtheye,对不起。我不明白。
    • 没有bytes 我们也会得到同样的结果,对吧?
    • @thefourtheye,OP 想要字符串。因此,将其显式转换为str(Python 2.x 中的bytes == str)。 bytearray 缺少一些方法。 (format, %),并且在被索引时工作方式不同。
    • 但是,在 Python 3.x 中,type(bytearray(data).decode())str。为什么我们需要bytes
    【解决方案2】:
    t = (83, 105, 101, 109, 101, 110, 115)
    print "".join(map(chr,t))
    Siemens
    

    【讨论】:

      【解决方案3】:

      对于数据中的每一个数字,应用chr函数得到对应的字符,然后将所有字符连接在一起得到实际的字符串,像这样

      print "".join(chr(item) for item in (83, 105, 101, 109, 101, 110, 115))
      # Siemens
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        • 1970-01-01
        • 2022-01-09
        • 2012-08-22
        相关资源
        最近更新 更多