我刚学会写python语言,我想怎么做换行输出呢?
我已经用谷歌搜索过了,但结果不在那里,或者不知道关键字
代码如下:
import binascii
filename = 'file.pdf'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))结果将如下所示,只有一行:255044462d312e340a25c3a4c3bcc3b6c39f0a322
但我想这样做,例如,在10个字符之后包装:0x25, 0x50, 0x44, ...
有谁可以帮我?谢谢!
发布于 2019-04-30 21:16:58
您可以使用textwrap模块来包装x个字符。
这是使用textwrap的代码。
import binascii
import textwrap
filename = 'file.pdf'
with open(filename, 'rb') as f:
content = f.read()
temp = binascii.hexlify(content)
temp_hex = []
# convert bytes to hexadecimal value
for t in temp:
temp_hex.append(hex(t))
# join the hexadecimal value using "," and wrap with maximum 10 characters each rows
print(textwrap.fill(",".join(temp_hex), 10))发布于 2019-04-30 21:02:18
编写一个生成器,将字符串拆分成大小相等的块,并使用它将字符串拆分成20个块,然后再分成长度为2的较小块:
def split_string(s, chunk_length):
for i in range(0, len(s), chunk_length):
yield s[i:i+chunk_length]
hex = binascii.hexlify(content)
for line in split_string(hex, 20): # divide into chunks of length 20
print(*split_string(line, 2), sep=", ") # then into chunks of length 2发布于 2019-04-30 21:08:52
首先,使用hex编写一个输出所需格式的custom_hexlify函数。
text = b'foo bar'
def custom_hexlify(data):
return ', '.join([hex(c) for c in data])
print(custom_hexlify(text)) # 0x66, 0x6f, 0x6f, 0x20, 0x62, 0x61, 0x72要对文本进行换行,可以使用textwrap.wrap。
def print_wrapped_line(*args, **kwargs):
for line in textwrap.wrap(*args, **kwargs):
print(line)
print_wrapped_line(custom_hexlify(text), 20)输出
0x66, 0x6f, 0x6f,
0x20, 0x62, 0x61,
0x72https://stackoverflow.com/questions/55921241
复制相似问题