In python, how would I convert a list of different length numbers to a list the same ascii characters?

89 Views Asked by At

I have a list of numbers:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]

I am trying to convert the list from integers to ascii characters of the same number before converting them to hex. I am running into trouble figuring out how to convert the entire list when there are some numbers with more than one digit.

I have tried:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
b = f'0x{ord(str(a)):x}'  
c = int(b, base=16)

which throws the error: ord() expected a character, but string of length 2 found.

A variation of it:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
separated_digits = [int(digit) for number in a for digit in str(number)]
ascii_chars_hexed = [f'0x{ord(str(digit)):x}' for digit in separated_digits]

works if I split the numbers in a into single digits, but I need the character output of the double digit numbers to be based upon the 2 digits rather than each individually.

I am expecting it to output:

[0x32, 0x32, 0x1e, 0x31, 0x1e, 0x36, 0x33, 0x1e, 0x30, 0x39, 0x34, 0x1e, 0x31, 0x1e, 0x31, 0x1d]`

Any thoughts?

1

There are 1 best solutions below

1
On BEST ANSWER

It's an odd data format, but the following does what you want. Convert the single-digit numbers to a string and get their ASCII value. It would make more sense to store the ASCII value of the '2' in the string as the integer 50 to begin with, for example.

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
print([f'{ord(str(n)) if n < 10 else n:#x}' for n in a])

Output:

['0x32', '0x32', '0x1e', '0x31', '0x1e', '0x36', '0x33', '0x1e', '0x30', '0x39', '0x34', '0x1e', '0x31', '0x1e', '0x31', '0x1d']