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. It can't just replace all size-n tabs by n spaces though, since a tab could be 1 to n spaces. I'm really confused, so if anyone could just point me in the right direction I'd greatly appreciate it.
For instance, if tabstop is size 4 originally:
123\t123 = 123 123 #one space in between
but changed to tabstop 5:
123\t123 = 123 123 #two spaces in between
I think I need to pad the end of the string with spaces until string%n==0 and then chunk it, but I'm pretty lost at the moment..
This programm replaces all the tabs for spaces in a file:
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)
I use .replace function that is very simple:
For a tab length of 5:
Here is the easiest way
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
both the functions above will give the same value, but the second one is super awesome !