textwrap.dedent replaces tabs?

Frederic Rentsch anthra.norell at vtxmail.ch
Thu Dec 28 16:00:59 EST 2006


Tom Plunket wrote:
> Frederic Rentsch wrote:
>
>   
>> It this works, good for you. I can't say I understand your objective. 
>> (You dedent common leading tabs, except if preceded by common leading 
>> spaces (?)).
>>     
>
> I dedent common leading whitespace, and tabs aren't equivalent to
> spaces.
>
> E.g. if some text is indented exclusively with tabs, then the leading
> tabs are stripped appropriately.  If some other text is indented with
> common leading spaces, those are stripped appropriately.  If the text to
> be stripped has some lines starting with spaces and others starting with
> tabs, there are no /common/ leading whitespace characters, and thus
> nothing is stripped.
>
>   
Your rules seem incomplete. What if common tabs remain after stripping common white space? Does this never happen? Or can we hope it doesn't happen? To err on the side of caution I complete your rules and this is my (tested) attempt at expressing them pythonically. (I admit it does look awfully sevety-ish. Just a vulgar little function.)

Cheers

Frederic

-------------------------------------------------------------

def dedent (lines):

   leading_space_re = re.compile (' *')
   leading_tab_re   = re.compile ('\t*')
   number_of_lines = len (lines)

   while 1:
      common_space_length = common_tab_length = 100000
      for line in lines:
         if line:   # No '\n'
            try: common_space_length = min (common_space_length, len 
(leading_space_re.match (line).group ()))
            except AttributeError: pass
            try: common_tab_length = min (common_tab_length, len 
(leading_tab_re.match (line).group ()))
            except AttributeError: pass
      if 0 < common_space_length < 100000:
         for i in xrange (number_of_lines):
            lines [i] = lines [i][common_space_length:]
      elif 0 < common_tab_length < 100000:
         for i in xrange (number_of_lines):
            lines [i] = lines [i][common_tab_length:]
      else:
         break

   return lines





More information about the Python-list mailing list