我很困惑使用expandtabs时如何计算字符串的长度。我认为expandtabs用适当数量的空格替换制表符(每个制表符的默认空格数为8)。但是,当我使用不同长度和不同数量的选项卡的字符串运行命令时,长度计算与我认为的不同(即,每个选项卡并不总是导致每个实例的字符串长度增加8 “/ t”)。
下面是一个详细的脚本输出,其中的注释解释了我认为应该是上面执行的命令的结果。有人请说明使用扩展标签时如何计算长度?
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).
>>>
答案 0 :(得分:7)
就像在文本编辑器中输入制表符一样,制表符将长度增加到下一个8的倍数。
所以:
'\t'
本身就是8,显然。'\t\t'
是16。'abc\tabc'
从3个字符开始,然后一个标签将其推送到8,然后最后一个'abc'
将其从8推送到11 ... 'abc\tabc\tabc'
同样从3开始,标签将其变为8,另一个'abc'
变为11,然后另一个标签将其推至16,最后'abc'
将长度设为19 答案 1 :(得分:5)
该选项卡将列指针递增到8的下一个倍数:
>>> 'abc\tabc'.expandtabs().replace(' ', '*')
'abc*****abc'