1

I am trying to specify a standard binary format length from a variable but for some reason it never works. Am I doing the formatting wrong or the variable inclusion?

comp.write("{0:%ib}".format(I) % num_bits)

ValueError: Invalid conversion specification

2 Answers 2

3

Firstly, it's in the wrong order:

("{0:%ib}" % num_bits).format(I)

Secondly, this isn't the way to do it! Mixing up types of formatting operator implies you don't know it can be done together. You want:

"{:{}b}".format(I, num_bits)

and if you really want to do it in two steps:

"{{:{}b}}".format(num_bits).format(I)

The {{ and }} are escaped, so are transformed to single braces, after the first .format.

Sign up to request clarification or add additional context in comments.

1 Comment

"{:0{}b}".format(I, num_bits) was best answer. I forgot to include the leading zeros as well.
2

You're doing the interpolation the wrong way round. You'll need to resolve the %i before passing it to format. This would work:

comp.write(("{0:%ib}" % num_bits).format(I))

but is pretty horrible, you probably want to split it into two:

fmt = "{0:%ib}" % num_bits
comp.write(fmt.format(I))

2 Comments

Is there an order of operations in python??
Do you mean operator precedence? Of course, but that's not relevant. The way you had it, the % operates on the result of the format call, rather than being passed to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.