我希望能够在屏幕上打印大量数据,但我希望确保每行只有32个字符,字符串包含二进制数据,我希望能够在一行上打印32个字节,但我不知道如何使用python循环做到这一点。
for c in string_value:
print( hex(c) )上面的代码行得通,但每行只打印一个字符。如何在每个for循环中迭代超过1个字符。我在网上找过了,但想不出办法。
任何帮助都将不胜感激。提前感谢
发布于 2016-08-11 14:31:38
您可以通过使用从0到31的范围迭代字符串来创建字符串列表,并在每次迭代后添加到新的索引31,然后只需迭代新列表并打印结果:
my_string = "this is my really long string, really really, string,
really really, string, really really, string, really really long..."
for elem in [my_string[i:i+31] for i in range(0, len(my_string), 31)]:
print elem您还可以阅读有关isslice的文章,它可以提供更优雅的解决方案。
发布于 2016-08-11 14:37:23
您可以懒惰地将可迭代程序分成块。
from itertools import takewhile, count, islice
def slice_iterable(iterable, chunk):
_it = iter(iterable)
return takewhile(bool, (tuple(islice(_it, chunk)) for _ in count(0)))
for chunk in slice_iterable(it, 32):
print(chunk)发布于 2016-08-11 14:33:34
将元素分组为n长度组的另一种常见方法是:
for custom_string in map(''.join, zip(*[iter(really_long_string)]*32)):
print hex(custom_string)https://stackoverflow.com/questions/38888646
复制相似问题