How to replace custom tabs with spaces in a string

2020-04-02 10:21发布

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. It can't just replace all size-n tabs by n spaces though, since a tab could be 1 to n spaces. I'm really confused, so if anyone could just point me in the right direction I'd greatly appreciate it.

For instance, if tabstop is size 4 originally:

123\t123 = 123 123 #one space in between

but changed to tabstop 5:

123\t123 = 123  123 #two spaces in between

I think I need to pad the end of the string with spaces until string%n==0 and then chunk it, but I'm pretty lost at the moment..

11条回答
做自己的国王
2楼-- · 2020-04-02 11:16

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'
查看更多
我只想做你的唯一
3楼-- · 2020-04-02 11:21

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.

查看更多
迷人小祖宗
4楼-- · 2020-04-02 11:24

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)
查看更多
女痞
5楼-- · 2020-04-02 11:24

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
查看更多
小情绪 Triste *
6楼-- · 2020-04-02 11:24

Use the re.sub is enough.

def untabify(s, tabstop = 4):
    return re.sub(re.compile(r'\t'), ' '*tabstop, s)
查看更多
登录 后发表回答