The shortest ways I have found are:
n = 5
# Python 2.
s = str(n)
i = int(s)
# Python 3.
s = bytes(str(n), "ascii")
i = int(s)
I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible.
Is there a shorter, cleaner way that I have missed? I currently make a lambda expression to fix it with a new function, but maybe that’s unnecessary.
Answer 1:
To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string’s
encodemethod. If you don’t supply an encoding parameter'ascii'is used, which will always be good enough for numeric digits.In Python 2
str(n)already produces bytes; theencodewill do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It’s unnecessary work, but it’s harmless and is completely compatible with Python 3.Answer 2:
Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I’ll answer that question too. If you want to convert
10tob'10'use the answer above, but if you want to convert10tob'\x0a\x00\x00\x00'then keep reading.The
structmodule was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done withstruct.pack. There’s a format parameterfmtthat determines which conversion it should perform. For a 4-byte integer, that would beifor signed numbers orIfor unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.