-2

I'm new in Python and need to convert an array of integers into one in binary code.

s_str = "test"    
s_acii = [ord(c) for c in s_str]
print(s_acii)
>> [116, 101, 115, 116]

What I need:

>> [1110100, 1100101, 1110011, 1110100]

Thanks!

mafehx
  • 363
  • 2
  • 6
  • 14
  • 2
    Let me get this straight: You want decimal numbers that *look* like binary numbers? Are you sure you don't want the binary numbers as strings? – Aran-Fey Mar 18 '19 at 18:57
  • Try `list(map(bin,s_acii))` or `[x.lstrip('0b') for x in map(bin,s_acii)]` – mad_ Mar 18 '19 at 18:58
  • 1
    I'm voting to close this question as off-topic because we don't write code for you. Show us what you have tried – user1251007 Mar 18 '19 at 18:58

2 Answers2

1

You can use bin built-in function to convert the integers into their binary representations:

>>> l = [116, 101, 115, 116]
>>> [bin(i) for i in l]
['0b1110100', '0b1100101', '0b1110011', '0b1110100']

If you do not want the 0b prefix, use string formatting with binary integer representation:

>>> l = [116, 101, 115, 116]
>>> ["{0:b}".format(i) for i in l]
['1110100', '1100101', '1110011', '1110100']
kalehmann
  • 4,821
  • 6
  • 26
  • 36
0

You can use the str.format method with b as the presentation type:

print('[{}]'.format(', '.join(map('{:b}'.format, s_acii))))

This outputs:

[1110100, 1100101, 1110011, 1110100]
blhsing
  • 91,368
  • 6
  • 71
  • 106