[Tutor] How o convert spaces into tabs??

Martin Walsh mwalsh at mwalsh.org
Tue Jun 2 21:53:36 CEST 2009

vince spicer wrote:
> regex will do it
> import re
> line = re.sub(r"\s+", "\t", line)
> print line

The above replaces the newline, which reminds me that even seemingly
trivial uses of 're' can become not-so-trivial in a hurry.

In [1]: import re
In [2]: line = '1  2  3  4  5\n'
In [3]: re.sub('\s+', '\t', line)
Out[3]: '1\t2\t3\t4\t5\t'

Maybe this is closer to your intent, but I refuse to guarantee it ;)
Better to stick with str methods whenever possible.

In [4]: re.sub('[ ]+', '\t', line)
Out[4]: '1\t2\t3\t4\t5\n'


More information about the Tutor mailing list