ASCII字符串转换器的编号

时间:2016-03-28 05:13:54

标签: python list 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'。我遇到的问题是我想将整数分成正确的数字。

3 个答案:

答案 0 :(得分: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 :(得分:2)

另一种方法是使用Pandas

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

如果你想填充零和#34;傻瓜"你可以在

中使用zfill
temp = temp.zfill((1+len(temp)/3)*3)

答案 2 :(得分: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']