如何在python中将ascii值列表转换为字符串?

如何在python中将ascii值列表转换为字符串?,python,string,ascii,Python,String,Ascii,我在Python程序中得到了一个列表,其中包含一系列数字,这些数字本身就是ASCII值。如何将其转换为可以回显到屏幕上的“常规”字符串?您可能正在查找“chr()”: 与其他人的基本解决方案相同,但我个人更喜欢使用map而不是列表: >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(map(chr,L)) 'hello, world' 从也许不是像Pyhtonic那样的解决方案,但对于

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

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


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


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

也许不是像Pyhtonic那样的解决方案,但对于像我这样的noobs来说更容易阅读:

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

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

我已经对现有答案进行了计时。下面是要复制的代码。TLDR是
字节(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))

我敢打赌你是用
[ord(x)for x in'hello,world']
chars=[chr(I)for I in range(97,97+26)]创建了这个列表L的。请注意,在堆栈溢出时,通常会包含一些解释,说明为什么建议的方法会回答这个问题,特别是当问题比较老并且已经有了一个可接受的答案时。这个建议有什么不同?为什么要使用它来代替现有的答案?还包括您正在使用的python实现,因为这可能会影响基准数字。以下是如何检索该信息。@MutableSideEffect已完成。我马上就知道是CPython,但我不知道你能通过编程找到它
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()
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
    mystring = mystring + chr(char)
print mystring
Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))
 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
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))