Python - Two Ways To Realize Conversion Between int & str

实现整数和字符串互转的两种方式。

Note: This article discusses the int and str interconversion is not a simple basic data interconversion, but more universal, the content will involve bytes and other transit operations required data types.

本文讨论的整数与字符串互转不是简单的基础数据互转,而是比较普适的,内容将涉及字节等中转操作所需数据类型。

Talk is cheap, let's enjoy the code directly.

str -> int

def str2int(s):
    return int.from_bytes(s.encode('utf-8'))

or

from binascii import hexlify

def str2int(s):
    return int(hexlify(s.encode('utf-8')), 16)

int -> str

def int2str(i):
    hexstr = hex(i)[2:]
    hexstr = '0' * (len(hexstr) % 2) + hexstr
    return bytes.fromhex(hexstr).decode('utf-8')

or

from binascii import unhexlify

def int2str(i):
    hexstr = hex(i)[2:]
    hexstr = '0' * (len(hexstr) % 2) + hexstr
    return unhexlify(hexstr).decode('utf-8')

You might be confused about these two lines of code:

hexstr = hex(i)[2:]
hexstr = '0' * (len(hexstr) % 2) + hexstr

It's easy to understand what the result will be: hexstr will be processed into a str of even length.

No matter binascii.unhexlify and bytes.fromhex, the required argument, a hexadecimal string, all require even lengths.

But this point is only made in the comments of the former (a function in a Python's built-in standard library), which leads to an insurmountable hurdle for a lot of beginners - they (including me at the beginning) don't know when to add zeros to not have a bug.


Finally, I should point out that the technical issues mentioned in this article are used in my latest project. I've just open-sourced the first version of it, you can view it on Github (by the way, give me a star)!

阅读剩余
THE END