AntoineLB
AntoineLB

Reputation: 482

Python : special char to binary

I'm using the answer i saw here.

My function is

def to_bin(s):
    return ' '.join(format(x, 'b') for x in bytearray(s))

It was working really well until i tried to convert a '%' character, i get the output :

>>>to_bin('%')
'100101'

while my expected result is :

>>>to_bin('%')
'0100101'

Do any of you have a solution ?

Thanks in advance.

Upvotes: 3

Views: 443

Answers (1)

tttapa
tttapa

Reputation: 1417

Just change your format specifier to pad with zeros to seven characters:

def to_bin(s): 
    return ' '.join(format(x, '07b') for x in bytearray(s))

Upvotes: 4

Related Questions