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

前端 未结 12 2164
無奈伤痛
無奈伤痛 2021-01-17 15:13

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.

12条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 15:29

    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()
    

提交回复
热议问题