2010-04-17 183 views
4

當我使用expandtabs時,如何計算字符串的長度,我感到困惑。我認爲expandtabs會用適當數量的空格替換標籤(默認每個標籤的空格數爲8)。但是,當我使用不同長度的字符串和不同數量的選項卡運行命令時,長度計算與我認爲的不同(即,每個選項卡並不總是導致每個實例的字符串長度增加8 「/ t」)。Python展開製表符長度計算

下面是一個詳細的腳本輸出和註釋,解釋了我認爲應該是上面執行的命令的結果。請有人解釋當使用展開標籤時如何計算長度?

IDLE 2.6.5  
>>> s = '\t' 
>>> print len(s) 
1 
>>> #the length of the string without expandtabs was one (1 tab counted as a single space), as expected. 
>>> print len(s.expandtabs()) 
8 
>>> #the length of the string with expandtabs was eight (1 tab counted as eight spaces). 
>>> s = '\t\t' 
>>> print len(s) 
2 
>>> #the length of the string without expandtabs was 2 (2 tabs, each counted as a single space). 
>>> print len(s.expandtabs()) 
16 
>>> #the length of the string with expandtabs was 16 (2 tabs counted as 8 spaces each). 
>>> s = 'abc\tabc' 
>>> print len(s) 
7 
>>> #the length of the string without expandtabs was seven (6 characters and 1 tab counted as a single space). 
>>> print len(s.expandtabs()) 
11 
>>> #the length of the string with expandtabs was NOT 14 (6 characters and one 8 space tabs). 
>>> s = 'abc\tabc\tabc' 
>>> print len(s) 
11 
>>> #the length of the string without expandtabs was 11 (9 characters and 2 tabs counted as a single space). 
>>> print len(s.expandtabs()) 
19 
>>> #the length of the string with expandtabs was NOT 25 (9 characters and two 8 space tabs). 
>>> 

回答

6

就像當你在一個文本編輯器輸入標籤,製表符增加長度的8

所以接下來的倍數:

  • '\t'本身是8,明顯。
  • '\t\t'是在3個字符16
  • 'abc\tabc'開始,然後一個標籤將其推到8,然後將最後'abc'從8至11將其推...
  • 'abc\tabc\tabc'同樣開始於3,選項卡凸塊它至圖8,另一個'abc'前進到11,則另一個選項卡它推至16,和最終'abc'帶來的長度至19
+0

很好的解釋如何列指針被推到8的下一個倍數。謝謝。 – Mithrill 2010-04-17 03:14:13

4

翼片遞增列指針的8的倍數:

>>> 'abc\tabc'.expandtabs().replace(' ', '*') 
'abc*****abc' 
+0

謝謝。我已經從我從您和Mark收到的答案中獲得了知識,並擴展了Python編程的Wikibook。 http://en.wikibooks.org/wiki/Python_Programming/Strings#expandtabs – Mithrill 2010-04-17 03:50:43

+0

@Mithrill:將列指針移動到N的下一個倍數而不是添加N個空格不是Python特有的......這只是標籤的工作方式;請參閱http://en.wikipedia.org/wiki/Tab_key – 2010-04-17 13:30:57