I\'m trying to write a python function not using any modules that will take a string that has tabs and replace the tabs with spaces appropriate for an inputted tabstop size.
Here is the easiest way
def replaceTab(text,tabs)
return text.replace('\t', ' ' * tabs)
For a tab length of 5:
>>> s = "123\t123"
>>> print ''.join('%-5s' % item for item in s.split('\t'))
123 123
>>>
I think Remi's answer is the simplest but it has a bug, it doesn't account for the case when you are already on a "tab stop" column. Tom Swirly pointed this out in the comments. Here's a tested fix to his suggestion:
def replace_tab(s, tabstop = 4):
result = str()
for c in s:
if c == '\t':
result += ' '
while ((len(result) % tabstop) != 0):
result += ' '
else:
result += c
return result
I needed something similar, here's what I came up with:
import re
def translate_tabs(tabstop = 8):
offset = [0]
def replace(match, offset=offset):
offset[0] += match.start(0)
return " " * (tabstop - offset[0] % tabstop)
return replace
re.sub(r'\t', translate_tabs(4), "123\t123")
# => '123 123'
re.sub(r'\t', translate_tabs(5), "123\t123")
# => '123 123'
This programm replaces all the tabs for spaces in a file:
def tab_to_space (line, tab_lenght = 8):
"""this function change all the tabs ('\\t') for spaces in a string,
the lenght of the tabs is 8 by default"""
while '\t' in line:
first_tab_init_pos = line.find('\t')
first_tab_end_pos = (((first_tab_init_pos // tab_lenght)+1) * tab_lenght)
diff = first_tab_end_pos - first_tab_init_pos
if diff == 0:
spaces_string = ' ' * tab_lenght
else:
spaces_string = ' ' * diff
line = line.replace('\t', spaces_string, 1)
return line
inputfile = open('inputfile.txt', 'r')
outputfile = open('outputfile.txt', 'w')
for line in inputfile:
line = tab_to_space(line)
outputfile.write(line)
inputfile.close()
outputfile.close()
if you have the requirement where you want to add n spaces instead of custom tab you can simply write below code. I have shown the implementation using two functions, each having different way to solve it.You can use any of the function!
for eg. let the string be in the variable 'code' and 'x' be the size of tab
code = "def add(x, y)\f\treturn x + y"
x=4
def convertTabs(code, x):
temp=""
for i in range(0,x):
temp+=" "
return code.replace("\t",temp)
def converTabs1(code,x):
return code.replace("\t",x*" ")
both the functions above will give the same value, but the second one is super awesome !