我很困惑使用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).
>>>
Run Code Online (Sandbox Code Playgroud)
就像在文本编辑器中输入制表符一样,制表符将长度增加到下一个8的倍数.
所以:
'\t' 显然,它本身就是8.'\t\t' 是16岁.'abc\tabc'从3个字符开始,然后一个标签将其推到8,然后最后一个'abc'将它从8推到11 ......'abc\tabc\tabc'同样从3开始,tab跳到8,另一个'abc'跳到11,然后另一个tab将它推到16,最后'abc'将长度调到19.该选项卡将列指针增加到8的下一个倍数:
>>> 'abc\tabc'.expandtabs().replace(' ', '*')
'abc*****abc'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6561 次 |
| 最近记录: |