2017年5月1日 星期一

[ Python 常見問題 ] Converting a number to binary with a fixed length

Source From Here
Question
Say I get a random number between 1 and 127. I change the number to binary and remove the 0b from it with the fallowing code:
  1. key_one= int(raw_input("Enter key (0 <= key <= 127): "))  
  2.   
  3. if key_one in range(128):  
  4.     bin_key_one=bin(key_one)[2:]  
  5. print bin_key_one  
  6. else:  
  7.     print "You have to enter key (0 <= key <= 127)"  
Now I want to make it 7-characters long by padding the beginning with zeros as necessary. I think I need to use a for loop, but can someone show me how to do it?

How-To
You can leverage the String Formatting. e.g.
>>> key_one = 4
>>> bin_key_one=bin(key_one )[2:] // Remove the prefix '0b'
>>> bin_key_one
'100'
>>> bin(key_one)
'0b100'
>>> '{0:07b}'.format(key_one) // Print the first input argument as binary string with fixed length=7
'0000100'


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...