faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Converter space indentation -> tab indentation

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 319, Charles G Waldman


"""
Packages: text
"""
"""
> I'm looking for a converter that converts Python files
> with space indentation  -> tab indentation.
How about this? 
"""
#!/usr/bin/env python
import sys, re
ws = re.compile("[ \t]+")
while 1:
    l=sys.stdin.readline()
    if not l:
        break
    w = ws.match(l)
    if w:
        nw = w.regs[0][1]
    else:
        nw=0
    tab, space = divmod(nw,8)
    sys.stdout.write('\t'*tab + ' '*space + l[nw:])