4

I want to pick a number from a given list list and extract the places of ones from n bits representation.

I know that if I want 8 bits, I need to write

r = random.choice(list)
bin = "{0:08b}".format(r)

but I want to do something like

bin = "{0:0(self.n)b}".format(r)

where n is a class member.

How do I do this?

2 Answers 2

3

You can use a nested a {…} to define the size:

bin = "{0:0{1}b}".format(r, self.n)

And with Py2.7+ you can omit the numbers if you find that cleaner:

bin = "{:0{}b}".format(r, self.n)

For example:

>>> "{:0{}b}".format(9, 8)
'00001001'
Sign up to request clarification or add additional context in comments.

Comments

1

From python3.6 on you will be able to use Literal String Interpolation, adding the variable names to your string.

In [81]: pad,num = 8,9

In [82]: f"{num:0{pad}b}"
Out[82]: '00001001'

Using str.format, you can also use names:

In [92]: pad,num = 8,9

In [93]: "{n:0{p}b}".format(n=num, p=pad)
Out[93]: '00001001'

2 Comments

And I thought the PEP for this was a candidate for an April Fools joke ...
Although NB: 3.6 won't be released until the end of 2016

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.