Godspped
Godspped

Reputation: 743

Print string 32 characters at a time in Python

I want to be able to print on the screen a large amount of data, but I want to make sure each line has only 32 characters, the string contains binary data and I want to be able to do do 32 bytes on one line but I dont know how to do this with python loops.

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

The above works, but only prints one character per line as it should. How can I iterate more than 1 character per for loop. I searched online but couldnt figure out a way.

Any help would be greatly appreciated. Thanks in advance

Upvotes: 0

Views: 1375

Answers (4)

acw1668
acw1668

Reputation: 46761

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

Upvotes: 0

Eli Korvigo
Eli Korvigo

Reputation: 10513

You can lazily slice the iterable into chunks

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)

Upvotes: 2

Nehal J Wani
Nehal J Wani

Reputation: 16619

Another common way of grouping elements into n-length groups:

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

Upvotes: 0

Kobi K
Kobi K

Reputation: 7931

You can create a list of strings by iterating over the string using range from 0 to 31 and after each iteration add to the new index 31, Then just iterate the new list and print the result:

 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

You can also read about isslice which can supply a more elegant solution.

Upvotes: 4

Related Questions