Python allows some degree of functional programming. Using the reduce() function and the lambda form we can express the common tab ->spaces expansion routine in a simpler and more efficient way
1 2 3 4 5 6
# Amazing quick def expandtab(str,tab=8): return reduce(lambda a,b: a + ' '*(tab-len(a)%tab) + b, str.split('\t') )
Python users often forget the power of functional approaches. This recipe show how easy and fast a task can be if you just leave the classical imperative style (and even shows a possible use for reduce().
We don't need to use all the power of regexen, neither we need to explicitly process lists, reduce() handles quite everything for us.
Each element of the list resulting from str.split() got passed to the lambda function. The other argument to the lambda is the result from the previous computation. So at the first pass we translate a '\t' to spaces, than concatenate it to a newer piece and pass it to the next iteration. This way we expand each tab in turn, with a simple single function.
Note that even if everything was expressed as a single logical line, using lambda, you can extract that as an expand_single_tab(str1,str2,tablen) function.