Reputation: 26315
I am trying split an integer into a list and convert every element into it's ASCII character. I want something like this:
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'
Is there a way I can do this? I want it to work for any number such as '65066066065'
, which will return 'ABBA'
, or '70'
, which will return 'F'
. The issue I'm having is that I want to split the integers into the right numbers.
Upvotes: 4
Views: 1589
Reputation: 52071
Another way can be using 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']
And for your other example
>>> 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']
For 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']
If you want to make the padding of zeroes "fool-proof" you can use zfill
as in
temp = temp.zfill((1+len(temp)/3)*3)
Upvotes: 2
Reputation: 5279
How about something like this
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)]
Yields
['a', 'a', 'r', 'g', 'h']
Upvotes: 1
Reputation: 650
It seems that you take the decimal ascii values, so 3 digits are a char. Using x mod 1000, would give you the last three digits of the number. iterate on the number. Example code:
integer = 97097114103104
ascii_num = ''
while integer > 0:
ascii_num += chr(integer % 1000)
integer /= 1000
print ascii_num[::-1] #to Reverse the string
Upvotes: 3