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

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

    Sorry, i misread the question the first time.

    This is a recursive version that should work for any number of tabs in the input :

    def tabstop ( s , tabnum = 4):
        if not '\t' in s:
            return s
        l = s.find('\t')
        return s[0:l]+' '*(tabnum-l)+tabstop(s[l+1:],tabnum)
    
    0 讨论(0)
  • 2021-01-17 15:42

    Use the re.sub is enough.

    def untabify(s, tabstop = 4):
        return re.sub(re.compile(r'\t'), ' '*tabstop, s)
    
    0 讨论(0)
  • 2021-01-17 15:42

    Fix for @rémi answer This implementation honors the leading tab and any consecutive tabs

    def replace_tab(s, tabstop=4):
        result = str()
        for c in s:
            if c == '\t':
                if (len(result) % tabstop == 0):
                    result += ' ' * tabstop
                else:
                    while (len(result) % tabstop != 0):
                        result += ' '
            else:
                result += c
        return result
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-17 15:43

    This code can help you:

    initial_string = "My \tstring \ttest\t"
    block_size = "5"
    "".join([("{block_value:"+str(block_size)+"s}").format(block_value=block) 
        for block in initial_string.split("\t")])
    

    You will need to study: format, split and join function and list comprehension concept.

    0 讨论(0)
  • 2021-01-17 15:47

    I use .replace function that is very simple:

    line = line.replace('\t', ' ')
    
    0 讨论(0)
提交回复
热议问题