I wonder, how can I increment a string representing a binary number, all the way up to another binary number? (for use in a while loop, for example).
For example I start with “0000” and after 15 incs, I should reach “1111” (in other words: “0000”, “0001”, “0010”, …, “1111”). At first this problem seemed really simple, but the only solutions I could come up with were quite ridiculous (not pythonic, some might say). Does anyone have an advice?
Thanks in advance!
To do what you literally asked for you should convert to an integer, add one, then change back to binary.
You may find the
binbuilt-in method useful in implementingto_binary, though you will need to modify its output slightly to match your desired result.However it would be better if possible to not convert back and forth: just store an integer and convert it to binary when you need to display it.
On reading your question carefully though, it seems that all you want to do is to generate the strings
'0000','0001','0010', etc. If this is correct, then I suggest usingitertools.product.Example:
See it working online: ideone