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.
Sorry, i misread the question the first time.
This is a recursive version that should work for any number of tabs in the input :
def tabstop ( s , tabnum = 4):
if not '\t' in s:
return s
l = s.find('\t')
return s[0:l]+' '*(tabnum-l)+tabstop(s[l+1:],tabnum)
Use the re.sub is enough.
def untabify(s, tabstop = 4):
return re.sub(re.compile(r'\t'), ' '*tabstop, s)
Fix for @rémi answer This implementation honors the leading tab and any consecutive tabs
def replace_tab(s, tabstop=4):
result = str()
for c in s:
if c == '\t':
if (len(result) % tabstop == 0):
result += ' ' * tabstop
else:
while (len(result) % tabstop != 0):
result += ' '
else:
result += c
return result
Since you wan't a python function that doesn't use any external module, I think you should design first the algorithm of your function...
I would propose to iterate on every char of the string ; if char i is a tab, you need to compute how many spaces to insert : the next "aligned" index is ((i / tabstop) + 1) * tabstop. So you need to insert ((i / tabstop) + 1) * tabstop - (i % tabstop). But an easier way is to insert tabs until you are aligned (i.e. i % tabstop == 0)
def replace_tab(s, tabstop = 4):
result = str()
for c in s:
if c == '\t':
while (len(result) % tabstop != 0):
result += ' ';
else:
result += c
return result
This code can help you:
initial_string = "My \tstring \ttest\t"
block_size = "5"
"".join([("{block_value:"+str(block_size)+"s}").format(block_value=block)
for block in initial_string.split("\t")])
You will need to study: format, split and join function and list comprehension concept.
I use .replace function that is very simple:
line = line.replace('\t', ' ')