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.

反观国内局域网上相关内容的技术文章,倒是基本不提这点,还很多重复内容,这就是信息封闭造成的又长又臭的抄袭链,竟还好意思说国内大循环?!

Translation: On the contrary, the technical articles on the network (especially the China LAN) of related content, not only a lot of repetition, but also basically do not mention this point (reflecting the plagiarism chain is long and smelly).


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)!

版权声明
作者:灰尘疾客
链接:https://www.gkcoll.xyz/559.html
来源:极客藏源
注意:若文章头部无特殊声明,则文章为作者原创,版权归作者所有,未经允许请勿转载(默认允许)。
转载须知:若无特殊说明,本站所有文章均遵循 CC BY-NC-SA 4.0 协议发布,转载、二次创作请遵守该协议内容,并参考以下文案添加转载声明:本文转载自网站 极客藏源 的用户 @灰尘疾客 的文章 《Python - Two Ways To Realize Conversion Between int & str》。本转载文发布遵循与原文相同的 CC BY-NC-SA 4.0 协议
THE END
分享
二维码
海报
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……
<<上一篇
下一篇>>