数字转ASCII字符串转换器

4
我正在尝试将一个整数分割成列表,并将每个元素转换为它的ASCII字符。我想要像这样的东西:
    integer = 97097114103104
    int_list = [97, 97, 114, 103, 104]

    chr(int_list[0]) = 'a'
    chr(int_list[1]) = 'a'
    chr(int_list[2]) = 'r'
    chr(int_list[3]) = 'g'
    chr(int_list[4]) = 'h'

    ascii_char = 'aargh'

有没有一种方法可以实现这个?我希望它适用于任何数字,例如'65066066065',它将返回'ABBA',或者'70',它将返回'F'。 我遇到的问题是我想把整数分成正确的数字。

3个回答

3

看起来你使用了十进制 ASCII 值,所以 3 个数字表示一个字符。 使用 x mod 1000,可以得到数字的最后三位。 对数字进行迭代。 示例代码:

integer = 97097114103104
ascii_num = ''
while integer > 0:
    ascii_num += chr(integer % 1000)
    integer /= 1000
print ascii_num[::-1] #to Reverse the string

2

另一种方法可以使用textwrap

>>> import textwrap
>>> integer = 97097114103104
>>> temp = str(integer) 
>>> temp = '0'+temp if len(temp)%3==2 else temp
>>> [chr(int(i)) for i in textwrap.wrap(temp,3)]
['a', 'a', 'r', 'g', 'h']

而对于您提到的另一个例子:
>>> import textwrap
>>> integer = 65066066065
>>> temp = str(integer) 
>>> temp = '0'+temp if len(temp)%3==2 else temp
>>> [chr(int(i)) for i in textwrap.wrap(temp,3)]
['A', 'B', 'B', 'A']

对于 integer = 102103

>>> import textwrap
>>> integer = 102103 
>>> temp = str(integer) 
>>> temp = '0'+temp if len(temp)%3==1 else temp
>>> [chr(int(i)) for i in textwrap.wrap(temp,3)]
['f', 'g']

如果您想使填充零更加“防傻”,您可以使用zfill,如下所示:
temp = temp.zfill((1+len(temp)/3)*3)

1
这样的东西怎么样?
integer = 97097114103104
#Add leaving 0 as a string
data='0'+str(integer)
d=[ chr(int(data[start:start+3])) for start in range(0,len(data),3)]

产量。
['a', 'a', 'r', 'g', 'h']

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