'{:08b}'.format(i)Python 2.x中的等价物

bre*_*ett 4 python binary string-formatting

我在Python 3中有一小段代码 -

'{:08b}' .format(i)
Run Code Online (Sandbox Code Playgroud)

这在Python 2.x中出错.有谁知道相同的?

Xio*_*ion 9

您的原始代码实际上适用于Python 2.7.对于Python 2.6,您需要引入对您的format参数的引用- 索引(0):

'{0:08b}'.format(i)
Run Code Online (Sandbox Code Playgroud)

或者名字:

'{x:08b}'.format(x=i)  # or:
'{i:08b}'.format(i=i)  # or even:
'{_:08b}'.format(_=i)  # (since you don't care about the name)
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这个特殊的怪癖似乎没有在关于字符串格式文档中提到:(

  • 怎么样''{0:08b}'.format(i)`?我认为这应该适用于python2.x和python3.x没有问题,它仍然使用像原始的位置参数... (2认同)