Passing indented code to compile()

Bengt Richter bokr at oz.net
Wed May 7 16:07:07 EDT 2003


On Wed, 07 May 2003 12:35:37 -0400, Lulu of the Lotus-Eaters <mertz at gnosis.cx> wrote:

>"John Wilson" <tug at wilson.co.uk> wrote previously:
>|"just working" it the apex of my ambition at the moment ;-)
>
>There is a function I use in several variants of my smart ASCII markup
>tools.  It looks at a code block (or anything), and pushes the block as
>far left as possible, while maintaining relative indents.
>
>    def LeftMargin(txt):
>        """Remove as many leading spaces as possible from whole block"""
>        for l in range(12,-1,-1):
>            re_lead = '(?sm)'+' '*l+'\S'
>            if re.match(re_lead, txt): break
>        txt = re.sub('(?sm)^'+' '*l, '', txt)
>        return txt
>
Hm, was this the intent?

 >>> print LeftMargin("""\
 ...     xxx
 ...    yyy
 ...      zzz
 ... """)
 xxx
    yyy
  zzz

Maybe (only tested as you see below):

 >>> def ljb(txt): # left justify block
 ...     lines = txt.splitlines()
 ...     lm = min([len(x)-len(x.lstrip()) for x in lines])
 ...     return '\n'.join([x[lm:] for x in lines])
 ...
 >>> print ljb("""\
 ...     xxx
 ...    yyy
 ...      zzz
 ... """)
  xxx
 yyy
   zzz

Regards,
Bengt Richter




More information about the Python-list mailing list