在Python中一次打印32个字符的字符串

时间:2016-08-11 06:20:17

标签: python python-2.7

我希望能够在屏幕上打印大量数据,但我想确保每行只有32个字符,字符串包含二进制数据,我希望能够在一个上执行32个字节但是我不知道如何用python循环来做这件事。

for c in string_value:
   print( hex(c) )

以上工作,但每行只打印一个字符。如何为每个循环迭代超过1个字符。我在网上搜索但是找不到方法。

非常感谢任何帮助。提前致谢

4 个答案:

答案 0 :(得分:4)

您可以通过使用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,它可以提供更优雅的解决方案。

答案 1 :(得分:1)

你可以懒洋洋地将迭代片段切成块

joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
    chicken = input("Why did the chicken cross the road?\n")
    if chicken in ["To get to the other side", "to get to the other side"]:
        print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
    print("Awww..")

答案 2 :(得分:0)

将元素分组为n长度组的另一种常用方法:

for custom_string in map(''.join, zip(*[iter(really_long_string)]*32)):
    print hex(custom_string)

答案 3 :(得分:0)

for i in range(0, len(string_value), 32): 
    print(string_value[i:i+32])