Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 231
Austin Avatar asked Apr 17 '13 06:04

Austin


People also ask

How do you replace a tab with 4 spaces in Notepad ++?

To convert existing tabs to spaces, press Edit->Blank Operations->TAB to Space .

How do you replace tabs with spaces in Python?

Use the str. replace() method to replace tabs with spaces, e.g. result = my_str. replace('\t', ' ') .


1 Answers

Here is the easiest way

def replaceTab(text,tabs)
    return text.replace('\t', ' ' * tabs)
like image 72
Vignesh A Avatar answered Sep 22 '22 21:09

Vignesh A