How to replace custom tabs with spaces in a string, depend on the size of the tab?

For a tab length of 5:

>>> s = "123\t123"
>>> print ''.join('%-5s' % item for item in s.split('\t'))
123  123  
>>> 

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

I use .replace function that is very simple:

line = line.replace('\t', ' ')