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
How to replace tabs in a string?
提问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)