Search code examples
pythonpython-3.xbinarynumbersseparator

Add underscore as a separator in a binary number in Python


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?


Solution

  • One way:

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

    output:

    '0_0000_0000_0001_0010'