Ad

How Can I Set The Number Of Bytes To Be Displayed By The Binary Form Of A Character In Python?

- 1 answer

I want to be able to set the number of bytes displayed by each character in the string to be 6. Here, the string is jJ and I'm getting the output as 1000111001. J is giving 1001 and I want it to display 001001 instead.

a = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/']
def mapFirst(string):
   return ''.join(bin(ord(chr(a.index(c)))) for c in string).replace('0b','')

def main():
    k = 'jJ'
    print(mapFirst(k))

if __name__ == "__main__":
  main()
Ad

Answer

Change:

return ''.join(bin(ord(chr(a.index(c)))) for c in string).replace('0b','')

With:

return ''.join(str(bin(ord(chr(a.index(c))))).replace('0b','').zfill(6) for c in string)

The function you were looking for is zfill(width)


Note: I suggest you to split that line into multiple lines for readability purposes.

Ad
source: stackoverflow.com
Ad