字符串上的Python3 expandtab无法正常工作

时间:2018-02-12 00:22:58

标签: python-3.x replace tabs spaces

AAPL,Feb,16,18,165.00,156.41,8.59,0.32,20998.  
AAPL,Feb,16,18,170.00,156.41,13.59,0.08,10177.  
AAPL,Feb,16,18,135.00,156.41,-21.41,0.18,11243.   
ABX,Feb,16,18,14.00,13.06,0.94,0.1,1251.  
AKS,Feb,16,18,5.00,4.5,0.5,0.05,1428.  

for linet in filein:
    linet = linet.replace(",","\t")
    linet = linet.expandtabs(12)    


123456789012345678901234567890123456789012345678901234567890.   

AAPL        Feb         16          18          165.00      156.41      8.59        0.32        20998.  
AAPL        Feb         16          18          170.00      156.41      13.59       0.08        10177.  
AAPL        Feb         16          18          135.00      156.41      -21.41      0.18        11243.  
ABX         Feb         16          18          14.00       13.06       0.94        0.1         1251.  
AKS         Feb         16          18          5.00        4.5         0.5         0.05        1428.  
AMD         Feb         16          18          12.00       11.31       0.69        0.12        9231.  

此代码似乎使用标准的8个空格而不是12个 已尝试过许多不同的标签宽度仍然相同

1 个答案:

答案 0 :(得分:1)

str.expandtabs(N)"\t"字符扩展为最多(但并非总是完全)N个空格,以带您进入下一个制表符< / em>的。标签停在(N*i)字符的位置,其中i是整数。在您的示例中,每列都从(12*i)位置开始。