Python 如何替换字符串中的制表符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29138054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:07:49  来源:igfitidea点击:

How to replace tabs in a string?

python

提问by PierreTroodoo

I need to replace tabs in a string, but only the tabs, not the spaces.

我需要替换字符串中的制表符但只替换制表,而不是空格。

If I use the str.replace() function, what would go in the first set of quotes?

如果我使用 str.replace() 函数,第一组引号中会出现什么?

回答by Tritium21

In python string literals, the '\t' pair represents the tab character. So you would use mystring.replace('\t', 'any other string that you want to replace the tab with').

在 python 字符串文字中,'\t' 对代表制表符。所以你会使用mystring.replace('\t', 'any other string that you want to replace the tab with').

回答by Amadan

str.replace("\t", "TAB_WAS_HERE")

回答by Brian S

This is too late for original poster, but for those that follow ...

这对于原始海报来说为时已晚,但对于那些遵循...

def expandTab( txt, tabWidth=8):
out=[]
for line in txt.split('\n'):
    try:
        while True:
            i = line.index( '\t')
            if ( tabWidth > 0 ):
                pad = " " * (tabWidth - (i % tabWidth))
            else :
                pad = ""
            line = line.replace("\t", pad, 1)
    except:
        out.append(line)
return "\n".join(out)