當我使用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).
>>>
很好的解釋如何列指針被推到8的下一個倍數。謝謝。 – Mithrill 2010-04-17 03:14:13