057:タブと半角空白文字を変換する
タブを半角空白文字に展開するには expandtabs メソッドを使います。
>>> a='\tabc' >>> b=a.expandtabs(4) >>> b ' abc'
Ruby レシピブックと同じ、正規表現を使った方法を採ることもできます。
import re
def untabify(s, tabstop=8):
u"""
タブを半角空白文字に
"""
return re.sub(
'(.*?)\t',
lambda mo: (
mo.group(1) +
' ' * (tabstop - (len(mo.group(1)) % tabstop))
),
s)
def tabify(s, tabstop=8):
u"""
半角空白文字をタブに
"""
def repl(mo):
tab, space = divmod(len(untabify(mo.group(0), tabstop)), tabstop)
return '\t' * tab + ' ' * space
return re.sub('(?m)^[ \t]+', repl, s)