如何在Python中将ASCII值列表转换为字符串?

92

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

9个回答

164

你可能在寻找 'chr()':

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

13
我打赌你使用[ord(x) for x in 'hello, world']创建了那个列表L。 - zapstar
1
chars = [chr(i) for i in range(97, 97 + 26)] - FindOutIslamNow

28

与其他人相同的基本解决方案,但我个人更喜欢使用 map 而不是列表推导:


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

map()比列表推导式略快。 - Felix An

14

8
你可以使用bytes(list).decode()来实现这一点,而list(string.encode())则可将值还原回来。

8
l = [83, 84, 65, 67, 75]

s = "".join([chr(c) for c in l])

print s

6
也许不是那么Python风格的解决方案,但对像我这样的新手来说更易读:

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

3
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()

2

我已经计时了现有的答案。下面是重现代码。简而言之,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-bit),Windows 10,i7-2600 3.4GHz。

有趣的观察结果:

  • “官方”最快答案(由 Toni Ruža 转发)现在已经过时,但一旦修复,仍然基本上与第二名并列
  • 将映射序列连接起来的速度几乎是列表推导式的两倍
  • 列表推导式比非列表推导式更快

复现代码如下:

import array, string, timeit, random
from collections import namedtuple

# Thomas Wouters (https://dev59.com/4nVC5IYBdhLWcg3wykej#180615)
def test_join_iterator(seq):
    return ''.join(chr(c) for c in seq)

# community wiki (https://dev59.com/4nVC5IYBdhLWcg3wykej#181057)
def test_join_map(seq):
    return ''.join(map(chr, seq))

# Thomas Vander Stichele (https://dev59.com/4nVC5IYBdhLWcg3wykej#180617)
def test_join_list(seq):
    return ''.join([chr(c) for c in seq])

# Toni Ruža (https://dev59.com/4nVC5IYBdhLWcg3wykej#184708)
# 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://dev59.com/4nVC5IYBdhLWcg3wykej#34246694)
def test_naive_add(seq):
    output = ''
    for c in seq:
        output += chr(c)
    return output

# Timo Herngreen (https://dev59.com/4nVC5IYBdhLWcg3wykej#55509509)
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实现,因为这可能会影响基准测试数字。以下是如何检索该信息的方法 https://dev59.com/fGUq5IYBdhLWcg3wMNcK#14718168. - Empty Space
@MutableSideEffect 完成。我知道它是CPython,但我不知道你可以通过编程方式找到它。 - user13528444
这应该是被接受的答案。 - Greg0ry

0
Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))

2
请注意,在 Stack Overflow 上,习惯上需要包含一些解释为什么所提出的方法回答了问题 - 特别是当问题比较老旧并且已经有一个被接受的答案时。这个建议与现有答案有何不同之处,为什么会使用它? - Cindy Meister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接