Python's string format method can take a format spec.
>>> "{0:b}".format(10)
'1010'
bin
(
x
)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int
object, it has to define an __index__()
method that returns an integer.
New in version 2.6.
186
|
Python's string format method can take a format spec.
| |||
166
|
If you're looking for Example:
| ||||||||||||||||
|
28
|
No language or library will give its user base everything that they desire. If you're working in an envronment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example:
which will construct your binary string based on the decimal value. Fortunately, however, Python has something already built in, the ability to do operations such as The general idea is to use code from (in order of preference):
| ||||||||
|
15
|
As a reference:
This function can convert a positive integer as large as It can be modified to serve a much larger integer, though it may not be as handy as | ||||||||
|
13
|
If you want a textual representation without the 0b-prefix, you could use this:
When you want a n-bit representation:
| ||||||||||||||||||||
|
7
|
one-liner with lambda:
test:
but then :(
in compare to
| ||||
|
4
|
Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is struct | ||
2
|
output:
| |||
2
|
Summary of alternatives:
Contributors include John Fouhy, Tung Nguyen, mVChr, moose. and Martijn Pieters. | ||||
|
2
|
Yet another solution with another algorithm, by using bitwise operators.
A faster version without reversing the string.
| |||
1
|
Here is the code I've just implemented. This is not a method but you can use it as a ready-to-use function!
| |||
1
|
here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.
|
bin
(
x
)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int
object, it has to define an __index__()
method that returns an integer.
New in version 2.6.
str.format()
just to format one value is overkill. Go straight to theformat()
function:format(n, 'b')
. There is no need to parse out the placeholder and match it to an argument, go straight for the value formatting operation itself. Only usestr.format()
if you need to place the formatted result in a longer string (e.g. use it as a template). – Martijn Pieters♦ Dec 10 '15 at 10:23