你如何在 Python 中表达二进制文字? [英] How do you express binary literals in Python?
本文介绍了你如何在 Python 中表达二进制文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用 Python 文字将整数表示为二进制数?
我很容易找到十六进制的答案:
<预><代码>>>>0x12AF4783>>>0x100256和八进制:
<预><代码>>>>01267695>>>010064Python 中如何使用字面量表示二进制?
<小时>答案摘要
- Python 2.5 及更早版本:可以使用
int('01010101111',2)
表示二进制,但不能使用文字. - Python 2.5 及更早版本:无法表达二进制文字.
- Python 2.6 测试版:您可以这样做:
0b1100111
或0B1100111
. - Python 2.6 beta:还将允许
0o27
或0O27
(第二个字符是字母 O)表示八进制. - Python 3.0 测试版:与 2.6 相同,但不再允许使用旧的
027
八进制语法.
解决方案
供参考—未来 Python 的可能性:
从 Python 2.6 开始,您可以使用前缀 0b 或 0B 表示二进制文字:
您还可以使用新的 bin 函数来获取数字的二进制表示:
<预><代码>>>>垃圾箱(173)'0b10101101'开发版文档:Python 2.6 中的新功能
How do you express an integer as a binary number with Python literals?
I was easily able to find the answer for hex:
>>> 0x12AF
4783
>>> 0x100
256
and octal:
>>> 01267
695
>>> 0100
64
How do you use literals to express binary in Python?
Summary of Answers
- Python 2.5 and earlier: can express binary using
int('01010101111',2)
but not with a literal. - Python 2.5 and earlier: there is no way to express binary literals.
- Python 2.6 beta: You can do like so:
0b1100111
or0B1100111
. - Python 2.6 beta: will also allow
0o27
or0O27
(second character is the letter O) to represent an octal. - Python 3.0 beta: Same as 2.6, but will no longer allow the older
027
syntax for octals.
解决方案
For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B:
>>> 0b101111
47
You can also use the new bin function to get the binary representation of a number:
>>> bin(173)
'0b10101101'
Development version of the documentation: What's New in Python 2.6
这篇关于你如何在 Python 中表达二进制文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文