Search code examples
python-3.xpprint

Can I force pprint to print a set number of elements per line instead of width?


I have a list of of values and would like to print it in such a way that after a certain number of elements pprint forces a new line. I'm working with a dynamic data set and it's not possible to predict what the width of each new desired line will be. The elements themselves are exclusively strings and represent a boolean value. This is the desired effect:

[ o x x x o
  x o x x x
  x x o x o
  x o x o x 
  x x x x o ]

Solution

  • You can use textwrap for that. The specifics will depend on your code & what you want but here's an example:

    import random
    import textwrap
    
    some_booleans = [
        random.choice([True, False]) for _ in range(30)
    ]
    
    stringified = ''.join('x' if elem else 'o' for elem in some_booleans)
    adjusted_lines = textwrap.wrap(stringified, width=10)
    to_print = '\n'.join(adjusted_lines)
    
    print(to_print)
    

    Output:

    oxoxoxoxxo
    xxxxooxooo
    xxxxoxxxoo