textwrap.dedent replaces tabs?

Frederic Rentsch anthra.norell at vtxmail.ch
Sun Dec 17 09:35:05 EST 2006


Tom Plunket wrote:
> CakeProphet wrote:
>
>   
>> Hmmm... a quick fix might be to temporarily replace all tab characters
>> with another, relatively unused control character.
>>
>> MyString = MyString.replace("\t", chr(1))
>> MyString = textwrap.dedent(MyString)
>> MyString = MyString.replace(chr(1), "\t")
>>
>> Of course... this isn't exactly safe, but it's not going to be fatal,
>> if it does mess something up. As long as you don't expect receiving any
>> ASCII 1 characters.
>>     
>
> Well, there is that small problem that there are leading tabs that I
> want stripped.  I guess I could manually replace all tabs with eight
> spaces (as opposed to 'correct' tab stops), and then replace them when
> done, but it's probably just as easy to write a non-destructive dedent.
>
> It's not that I don't understand /why/ it does it; indeed I'm sure it
> does this so you can mix tabs and spaces in Python source.  Why anyone
> would intentionally do that, though, I'm not sure.  ;)
>
> -tom!
>
>   
This should do the trick:

 >>> Dedent = re.compile ('^\s+')
 >>> for line in lines: print Dedent.sub ('', line)

Frederic

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

Testing:

 >>> text = s = '''   # Dedent demo
No indent
   Three space indent
\tOne tab indent
   \t\tThree space, two tab indent
\t  \tOne tab, two space, one tab indent with two tabs here >\t\t<'''

 >>> print text
print s
   # Dedent demo
No indent
   Three space indent
    One tab indent
           Three space - two tab indent
           One tab - two spaces - one tab indent with two tabs here >    
    <

 >>> for line in text.splitlines (): print Dedent.sub ('', line)

# Dedent demo
No indent
Three space indent
One tab indent
Three space - two tab indent
One tab - two spaces - one tab indent with two tabs here >        <

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





More information about the Python-list mailing list