【问题标题】:How do I convert a list of ascii values to a string in python?如何在 python 中将 ascii 值列表转换为字符串?
【发布时间】:2010-09-15 21:18:18
【问题描述】:

我在 Python 程序中有一个列表,其中包含一系列数字,这些数字本身就是 ASCII 值。如何将其转换为可以回显到屏幕的“常规”字符串?

【问题讨论】:

    标签: python string ascii


    【解决方案1】:

    您可能正在寻找“chr()”:

    >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
    >>> ''.join(chr(i) for i in L)
    'hello, world'
    

    【讨论】:

    • 我敢打赌你使用[ord(x) for x in 'hello, world']创建了那个列表L
    • chars = [chr(i) for i in range(97, 97 + 26)]
    【解决方案2】:

    和其他人一样的基本解决方案,但我个人更喜欢使用地图而不是列表理解:

    
    >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
    >>> ''.join(map(chr,L))
    'hello, world'
    

    【讨论】:

      【解决方案3】:
      import array
      def f7(list):
          return array.array('B', list).tostring()
      

      来自Python Patterns - An Optimization Anecdote

      【讨论】:

        【解决方案4】:
        l = [83, 84, 65, 67, 75]
        
        s = "".join([chr(c) for c in l])
        
        print s
        

        【讨论】:

          【解决方案5】:

          您可以使用 bytes(list).decode() 执行此操作 - 并使用 list(string.encode()) 获取值。

          【讨论】:

            【解决方案6】:

            也许不像 Pyhtonic 一个解决方案,但对于像我这样的菜鸟来说更容易阅读:

            charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
            mystring = ""
            for char in charlist:
                mystring = mystring + chr(char)
            print mystring
            

            【讨论】:

              【解决方案7】:
              def working_ascii():
                  """
                      G    r   e    e    t    i     n   g    s    !
                      71, 114, 101, 101, 116, 105, 110, 103, 115, 33
                  """
              
                  hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
                  pmsg = ''.join(chr(i) for i in hello)
                  print(pmsg)
              
                  for i in range(33, 256):
                      print(" ascii: {0} char: {1}".format(i, chr(i)))
              
              working_ascii()
              

              【讨论】:

                【解决方案8】:

                我已经为现有答案计时。要重现的代码如下。 TLDR 是 bytes(seq).decode() 是迄今为止最快的。结果在这里:

                 test_bytes_decode : 12.8046 μs/rep
                     test_join_map : 62.1697 μs/rep
                test_array_library : 63.7088 μs/rep
                    test_join_list : 112.021 μs/rep
                test_join_iterator : 171.331 μs/rep
                    test_naive_add : 286.632 μs/rep
                

                设置为 CPython 3.8.2(32 位)、Windows 10、i7-2600 3.4GHz

                有趣的观察:

                • “官方”最快的答案(由 Toni Ruža 转发)现在对于 Python 3 来说已经过时了,但一旦修复,基本上仍然排在第二位
                • 加入映射序列的速度几乎是列表理解的两倍
                • 列表理解比它的非列表对应物更快

                要重现的代码在这里:

                import array, string, timeit, random
                from collections import namedtuple
                
                # Thomas Wouters (https://stackoverflow.com/a/180615/13528444)
                def test_join_iterator(seq):
                    return ''.join(chr(c) for c in seq)
                
                # community wiki (https://stackoverflow.com/a/181057/13528444)
                def test_join_map(seq):
                    return ''.join(map(chr, seq))
                
                # Thomas Vander Stichele (https://stackoverflow.com/a/180617/13528444)
                def test_join_list(seq):
                    return ''.join([chr(c) for c in seq])
                
                # Toni Ruža (https://stackoverflow.com/a/184708/13528444)
                # Also from https://www.python.org/doc/essays/list2str/
                def test_array_library(seq):
                    return array.array('b', seq).tobytes().decode()  # Updated from tostring() for Python 3
                
                # David White (https://stackoverflow.com/a/34246694/13528444)
                def test_naive_add(seq):
                    output = ''
                    for c in seq:
                        output += chr(c)
                    return output
                
                # Timo Herngreen (https://stackoverflow.com/a/55509509/13528444)
                def test_bytes_decode(seq):
                    return bytes(seq).decode()
                
                RESULT = ''.join(random.choices(string.printable, None, k=1000))
                INT_SEQ = [ord(c) for c in RESULT]
                REPS=10000
                
                if __name__ == '__main__':
                    tests = {
                        name: test
                        for (name, test) in globals().items()
                        if name.startswith('test_')
                    }
                
                    Result = namedtuple('Result', ['name', 'passed', 'time', 'reps'])
                    results = [
                        Result(
                            name=name,
                            passed=test(INT_SEQ) == RESULT,
                            time=timeit.Timer(
                                stmt=f'{name}(INT_SEQ)',
                                setup=f'from __main__ import INT_SEQ, {name}'
                                ).timeit(REPS) / REPS,
                            reps=REPS)
                        for name, test in tests.items()
                    ]
                    results.sort(key=lambda r: r.time if r.passed else float('inf'))
                
                    def seconds_per_rep(secs):
                        (unit, amount) = (
                            ('s', secs) if secs > 1
                            else ('ms', secs * 10 ** 3) if secs > (10 ** -3)
                            else ('μs', secs * 10 ** 6) if secs > (10 ** -6)
                            else ('ns', secs * 10 ** 9))
                        return f'{amount:.6} {unit}/rep'
                
                    max_name_length = max(len(name) for name in tests)
                    for r in results:
                        print(
                            r.name.rjust(max_name_length),
                            ':',
                            'failed' if not r.passed else seconds_per_rep(r.time))
                

                【讨论】:

                • 还包括您正在使用的 python 实现,因为这可能会影响基准数。以下是您如何检索该信息stackoverflow.com/a/14718168/12160191
                • @MutableSideEffect 完成。我知道它是 CPython,但我不知道你可以通过编程找到它
                • 这应该是被接受的答案。
                【解决方案9】:
                Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
                print(''.join(chr(number) for number in Question))
                

                【讨论】:

                • 请注意,在 Stack Overflow 上,习惯上会包含一些解释,说明所提议的方法为何会回答问题 - 特别是当问题较旧并且已经有可接受的答案时。这个建议有什么不同,为什么要用它来代替现有的答案?
                猜你喜欢
                • 2012-01-17
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-04-19
                • 2021-12-31
                • 1970-01-01
                相关资源
                最近更新 更多