Formatted printing of deep tuples

Mikael Olofsson mikael at isy.liu.se
Fri Oct 5 03:12:07 EDT 2001


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,'')

HTH

/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    05-Oct-2001
Time:    09:07:32

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by XF-Mail.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com




More information about the Python-list mailing list