Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将二进制文件转换为heximal文件,同时保留开头的零?_Python_Python 3.x_Python 3.7 - Fatal编程技术网

Python 如何将二进制文件转换为heximal文件,同时保留开头的零?

Python 如何将二进制文件转换为heximal文件,同时保留开头的零?,python,python-3.x,python-3.7,Python,Python 3.x,Python 3.7,以下是一个例子: >x=int(输入(“输入一些带有1和0的数字:”) 输入一些带有1和0的数字:001 10100 00010 1100100 1000 >>>y=#这里有一些代码 >>>打印(y) 001 14 0002 64 8 我应该为y分配什么?使用正则表达式获取前导零,然后将其余的转换为int,但将其格式化为十六进制 import re def formatter(s): """Convert binary string s to hex, but keep leadin

以下是一个例子:

>x=int(输入(“输入一些带有1和0的数字:”)
输入一些带有1和0的数字:001 10100 00010 1100100 1000
>>>y=#这里有一些代码
>>>打印(y)
001 14 0002 64 8

我应该为y分配什么?

使用正则表达式获取前导零,然后将其余的转换为int,但将其格式化为十六进制

import re

def formatter(s):
    """Convert binary string s to hex, but keep leading zeroes."""
    zeroes = re.match(r'0*', s)[0]
    binary = s[len(zeroes):]
    i = int(binary, 2)
    return '{}{:x}'.format(zeroes, i)

x = '001 10100 00010 1100100 1000'
y = ' '.join(map(formatter, x.split()))
print(y)

欢迎来到堆栈溢出!检查一下你尝试了什么?请显示您的尝试。打印前导零的规则是什么?这看起来完全是武断的。@DYZ我什么都没试过,我对pythonSO不是一个做作业的网站有点陌生。您应该带着一个特定的问题来到这里,并且您至少应该了解一些Python。