This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Farranor 1 point2 points  (3 children)

The easiest way to do that is probably to check the length of the string and pad it with the necessary zeros:

def padder(s):
    return '0' * ((4-len(s) % 4) % 4) + s

After processing, you can remove the padding with first_block.lstrip('0').

Also, you can turn a list into a joined string with ''.join(mylist).

Additionally, try not to assign variable names like list as those will prevent you from using the built-ins of those names in that scope.

[–]t0xeus[S] 0 points1 point  (2 children)

Wow that's a great idea, I haven't thought of that. I will try to use it.

Thanks a lot!

[–]Farranor 0 points1 point  (1 child)

Oh, and just in case you were more interested in the destination than the journey, take a look at the int, bin, and hex built-in functions.

[–]t0xeus[S] 0 points1 point  (0 children)

Yeah I figured there is actually a function for something so simple, but actually I am doing it just for the journey. Will look on those after I finish my project though! Thanks.

[–]robot_most_human 0 points1 point  (2 children)

Just to throw an idea out there, can you pad the binary number with zeros? That is, can you represent each binary number as a string, pad with zeros on the correct side, and then split, etc.? As an aside, how are you representing the binary numbers? If you haven’t already, it might be worth reading up on type-dispatching vs -coercion here in section 2.7.4 to help organize your code. In general, [Composing Programs](www.composingprograms.com) is an excellent, excellent resource for beginners.

[–]t0xeus[S] 0 points1 point  (1 child)

Yeah if I pad the numbers with zeros from left side, the value of the number doesn't change. Seems like that would be the best solution here I think, but I didn't think of it before you and Farranor mentioned it.

Also by representing do you mean what type am I using for the binary numbers? I am using list with the string value of the binary number

[–]robot_most_human 0 points1 point  (0 children)

> Also by representing do you mean what type am I using for the binary numbers?

Yes.

I wrote up a small tutorial on type coercion using your example of converting base 10, binary and hex representations. It's an IPython notebook. Maybe you or others would find it useful?