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

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

    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
    

提交回复
热议问题