How to replace custom tabs with spaces in a string

2020-04-02 10:21发布

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

11条回答
等我变得足够好
2楼-- · 2020-04-02 11:01

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()
查看更多
爷、活的狠高调
3楼-- · 2020-04-02 11:09

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
查看更多
Lonely孤独者°
4楼-- · 2020-04-02 11:11

I use .replace function that is very simple:

line = line.replace('\t', ' ')
查看更多
姐就是有狂的资本
5楼-- · 2020-04-02 11:13

For a tab length of 5:

>>> s = "123\t123"
>>> print ''.join('%-5s' % item for item in s.split('\t'))
123  123  
>>> 
查看更多
放我归山
6楼-- · 2020-04-02 11:14

Here is the easiest way

def replaceTab(text,tabs)
    return text.replace('\t', ' ' * tabs)
查看更多
劳资没心,怎么记你
7楼-- · 2020-04-02 11:16

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 !

查看更多
登录 后发表回答