0

我正在尝试将多个 ASCII 整数转换回 char 并将其作为单个字符串。我知道如何一一做到,但我想不出如何在一个循环中做到这一点。这是我必须在我的 ascii_message 变量中获取所有 ascii 整数的代码:

for c in ascii_message: 
    ascii_int = ord(c)

谢谢!

4

1 回答 1

5

在 Python 2 中执行此操作的一种有效方法是将列表加载到bytearray对象中,然后将其转换为字符串。像这样:

ascii_message = [
    83, 111, 109, 101, 32, 65, 83, 67, 
    73, 73, 32, 116, 101, 120, 116, 46,
]

a = bytearray(ascii_message)
s = str(a)
print s

输出

Some ASCII text.

这是一个在 Python 2 和 3 中都能正常工作的变体。

a = bytearray(ascii_message)
s = a.decode('ASCII')

但是,在 Python 3 中,使用不可变bytes对象而不是可变对象更为常见bytearray

a = bytes(ascii_message)
s = a.decode('ASCII')

bytearray在 Python 2 和 3 中,也可以使用 a 有效地完成相反的过程。

s = 'Some ASCII text.'
a = list(bytearray(s.encode('ASCII')))
print(a)

输出

[83, 111, 109, 101, 32, 65, 83, 67, 73, 73, 32, 116, 101, 120, 116, 46]

如果您的“数字列表”实际上是一个字符串,您可以将其转换为像这样的正确整数列表。

numbers = '48 98 49 48 49 49 48 48 48 49 48 49 48 49 48 48'
ascii_message = [int(u) for u in numbers.split()]
print(ascii_message)

a = bytearray(ascii_message)
s = a.decode('ASCII')
print(s)

输出

[48, 98, 49, 48, 49, 49, 48, 48, 48, 49, 48, 49, 48, 49, 48, 48]
0b10110001010100

这看起来是 14 位数字的二进制表示。所以我想还有进一步的步骤来解决这个难题。祝你好运!

于 2017-10-13T02:07:05.140 回答