2016-03-28 116 views
4

我想分割一个整数到列表中,并将每个元素转换为它的ASCII字符。我想要这样的事情:数字到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'。我遇到的问题是我想将整数分成正确的数字。

+0

为什么会是[[9 7,97,...]'而不是'[9,70,97,...]'? – mgilson

+0

@mgilson预先设置0将长度变成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 
+1

我在想一些类似的东西,我认为你应该检查它是一个100以下的ascii代码的情况。像97,以防在那之前没有0。 – Olegp

+1

但是,这是因为它是在数字的开头,所以这个代码没有问题,例如在它的数字中间保存为097 –

+1

是的,前97个将被最后吃掉,这意味着它没有问题,但在那里不保证没有0.中间不会有另外的97.如果在第一次输入后承诺0,那么你的代码就是成品。 – Olegp

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'] 
+1

你是怎么得到'integer ='097097114103104'的?在OP的例子中它是'integer = 97097114103104' –

+1

我编辑了起始值! –

+1

整数= 97097114103104 data ='0'+ str(整数) –

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

@Opticgenius是的,'进口textwrap'。我会补充说, –

+1

谢谢,我也喜欢这种方法。 – RoadRunner

+1

不客气,很乐意帮忙 –