Formatted printing of deep tuples

Richard Jones richard at bizarsoftware.com.au
Fri Oct 5 03:30:41 EDT 2001


On Friday 05 October 2001 17:12, Mikael Olofsson wrote:
> On 05-Oct-2001 Ignacio Vazquez-Abrams wrote:
>  >  Okay, here's a good one. Say I have a tuple as follows:
>  >
>  >  ---
>  >  (((1, 2),), ((), ('a', (('b', 'c'),))))
>  >  ---
>  >
>  >  Does anyone have or know of any code that will format it similar to:
>  >
>  >  ---
>  >  (
>  >    (
>  >      (
>  >        1, 2
>  >      ),
>  >    ),
>  >    (
>  >      (
>  >      ),
>  >      (
>  >        'a',
>  >        (
>  >          (
>  >            'b', 'c'
>  >          ),
>  >        )
>  >      )
>  >    )
>  >  )
>
> I'm sure someone else has a one-liner using regexps, but the following
> seems to be doing the trick.
>
> def test(a,indent=2):
>     import string
>     a=str(a)
>     s=[]
>     i=0
>     f=0
>     for x in a:
>         if x=='(':
>             s.append('\n'+i*' '+'(')
>             i=i+indent
>             f=1
>         elif x==')':
>             i=i-indent
>             s.append('\n'+i*' '+')')
>             f=0
>         else:
>             if f:
>                 s.append('\n'+i*' ')
>                 f=0
>             s.append(x)
>     return string.join(s,'')

Bored. Wrote this:

def format_tuple(out, tuple, indent=''):
    out('%s(\n'%indent)
    new_indent = indent+'  '
    for element in tuple:
        if type(element) == type(()):
            format_tuple(out, element, new_indent)
        else:
            out('%s%r,\n'%(new_indent, element))
    out('%s)\n'%indent)

import sys
out = sys.stdout.write
format_tuple(out, (((1, 2),), ((), ('a', (('b', 'c'),)))))


Might write another before I go home ;)


     Richard




More information about the Python-list mailing list