[Baypiggies] Discussion for newbies/beginner night talks

Doug Landauer zia at cruzio.com
Sat Feb 10 09:42:21 CET 2007


On Feb 10, 2007, at 12:27 AM, Doug Landauer wrote:
> For what it's worth, here's my version.  It was inspired by Hal
> Fulton's "margin" method from his Ruby book.  It works at runtime, and
> isn't as strict as the cookbook example that Michael Bernstein
> mentioned (
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/145672 ), but
> it's short and a bit easier to use (less cluttered-looking at usage
> site) than Chad's more efficient compile-time version.
>
> import re
> undent_pat = re.compile( r"(?m)^\s*\S(.*)$", re.M  )
> def undent (str):
>      return undent_pat.sub( r'\1', str.rstrip() )

Always happens just *after* I post ...

I merged a couple of versions of that pattern, and now the initial (?m) 
is redundant.
Removing it makes the pattern easier to understand:

   undent_pat = re.compile( r"^\s*\S(.*)$", re.M  )

With the M (multiline) mode, ^ matches beginning of any line in the 
string, and $ matches the ends of them.

So you can use an even shorter version:

import re
def undent (str):
     return re.sub( r'(?m)^\s*\S(.*)$', r'\1', str.rstrip() )

if you don't care about the regex getting recompiled at each usage.

  -- Doug L.



More information about the Baypiggies mailing list