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

前端 未结 12 2069
無奈伤痛
無奈伤痛 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:25

    I think Remi's answer is the simplest but it has a bug, it doesn't account for the case when you are already on a "tab stop" column. Tom Swirly pointed this out in the comments. Here's a tested fix to his suggestion:

    def replace_tab(s, tabstop = 4):
        result = str()
    
        for c in s:
            if c == '\t':
                result += ' '
                while ((len(result) % tabstop) != 0):
                    result += ' '
            else:
                result += c    
    
        return result
    

提交回复
热议问题