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

五迷三道 提交于 2019-12-01 15:32:32

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

For a tab length of 5:

>>> s = "123\t123"
>>> print ''.join('%-5s' % item for item in s.split('\t'))
123  123  
>>> 

I use .replace function that is very simple:

line = line.replace('\t', ' ')

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)

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

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.

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

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 !

I needed something similar, here's what I came up with:

import re

def translate_tabs(tabstop = 8):
  offset = [0]
  def replace(match, offset=offset):
    offset[0] += match.start(0)
    return " " * (tabstop - offset[0] % tabstop)
  return replace

re.sub(r'\t', translate_tabs(4), "123\t123") 
# => '123 123'

re.sub(r'\t', translate_tabs(5), "123\t123")
# => '123  123'

Use the re.sub is enough.

def untabify(s, tabstop = 4):
    return re.sub(re.compile(r'\t'), ' '*tabstop, s)

Here is the easiest way

def replaceTab(text,tabs)
    return text.replace('\t', ' ' * tabs)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!