Add underscore as a separator in a binary number in Python

Viewed 466

I a trying to convert a decimal number into a 17-bit binary number and add underscore as a separator in it. I am using the following code -

id = 18
get_bin = lambda x, n: format(x, 'b').zfill(n)
bin_num = get_bin(id, 17)

The output I am getting is in the form of -

00000000000010010

I am trying to get the following output -

0_0000_0000_0001_0010

How can I get it?

3 Answers

One way:

import textwrap
result = '_'.join(textwrap.wrap(bin_num[::-1], 4))[::-1]

output:

'0_0000_0000_0001_0010'

You need to add the _ to the format string, and also you don't need to use zfill - 017_b formats to a minimum length of 17 characters, zero filling the space, and using _ in between.

print(format(18, '021_b')) 

gives

0_0000_0000_0001_0010

Also note in binary mode, the underscores are always every 4 digits as you require there. More

Related