Для python2.7 или лучше: (. В python2.6, используйте '{0:050b}'
вместо '{:050b}'
)
In [83]: import random
In [84]: '{:050b}'.format(random.randrange(1<<50))
Out[84]: '10011110110110000011111000011100101111101001001011'
Объяснение:
Метод string.format
может преобразовывать целые числа в их двоичные представления строк. Основной код формата сделать это '{:b}'
:
In [91]: '{:b}'.format(10)
Out[91]: '1010'
Чтобы сделать строку шириной 50, используйте код формата '{:50b}'
:
In [92]: '{:50b}'.format(10)
Out[92]: ' 1010'
и заполнить пробелы с нулями, используйте {:050b}
:
In [93]: '{:050b}'.format(10)
Out[93]: '00000000000000000000000000000000000000000000001010'
syntax for str.format Сначала немного сложнее. Вот моя шпаргалка:
http://docs.python.org/library/string.html#format-string-syntax
replacement_field ::= "{" field_name ["!" conversion] [":" format_spec] "}"
field_name ::= (identifier|integer)("."attribute_name|"["element_index"]")*
attribute_name ::= identifier
element_index ::= integer
conversion ::= "r" | "s"
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <a character other than '}'>
align ::= "<" | ">" | "=" | "^"
"=" forces the padding to be placed after the sign (if any)
but before the digits. (for numeric types)
"<" left justification
">" right justification
"^" center justification
sign ::= "+" | "-" | " "
"+" places a plus/minus sign for all numbers
"-" places a sign only for negative numbers
" " places a leading space for positive numbers
# for integers with type b,o,x, tells format to prefix
output with 0b, 0o, or 0x.
0 enables zero-padding. equivalent to 0= fill align.
width ::= integer
, tells format to use a comma for a thousands separator
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" |
"o" | "x" | "X" | "%"
c convert integer to corresponding unicode character
n uses a locale-aware separator
% multiplies number by 100, display in 'f' format, with percent sign
перфекционист? '' – wim