在python中通过寻找非零ch来拆分字符串

2024-10-01 04:46:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想进行以下拆分:

input: 0x0000007c9226fc output: 7c9226fc
input: 0x000000007c90e8ab output: 7c90e8ab
input: 0x000000007c9220fc output: 7c9220fc

我使用下面的代码行来完成此操作,但它不起作用!在

^{pr2}$

我得到的这些输出是错误的!在

input: 0x000000007c90e8ab output: e8ab
input: 0x000000007c9220fc output: fc

做这种分割最快的方法是什么? 我现在唯一的想法是做一个循环并执行检查,但这有点耗时。在

我要指出的是,输入中的零的数目是不固定的。在


Tags: 方法代码inputoutput错误fc数目耗时
3条回答

使用int()可以将每个字符串转换为以16为基数的整数。然后转换回字符串。在

for s in '0x000000007c9226fc', '0x000000007c90e8ab', '0x000000007c9220fc':
    print '%x' % int(s, 16)

输出

^{pr2}$
input[2:].lstrip('0')

那应该行了。[2:]跳过前导的0x(我假设它总是在那里),然后{}会从左边删除所有的零。在

实际上,我们可以使用lstrip功能删除多个前导字符来简化:

^{pr2}$

format非常方便:

>>> print '{:x}'.format(0x000000007c90e8ab)
7c90e8ab

>>> print '{:x}'.format(0x000000007c9220fc)
7c9220fc

相关问题 更多 >