Wut*_*Wut 7 python python-2.7 python-3.x
我正在学习Python并使用Python获得expandtabs命令.这是文档中的官方定义:
Run Code Online (Sandbox Code Playgroud)string.expandtabs(s[, tabsize])展开字符串中的选项卡,将其替换为一个或多个空格,具体取决于当前列和给定的选项卡大小.在字符串中出现每个换行符后,列号将重置为零.这不了解其他非打印字符或转义序列.选项卡大小默认为8.
所以我从中理解的是,制表符的默认大小是8,为了增加它,我们可以使用其他值
所以,当我在shell中尝试它时,我尝试了以下输入 -
>>> str = "this is\tstring"
>>> print str.expandtabs(0)
this isstring
>>> print str.expandtabs(1)
this is string
>>> print str.expandtabs(2)
this is string
>>> print str.expandtabs(3)
this is string
>>> print str.expandtabs(4)
this is string
>>> print str.expandtabs(5)
this is string
>>> print str.expandtabs(6)
this is string
>>> print str.expandtabs(7)
this is string
>>> print str.expandtabs(8)
this is string
>>> print str.expandtabs(9)
this is string
>>> print str.expandtabs(10)
this is string
>>> print str.expandtabs(11)
this is string
Run Code Online (Sandbox Code Playgroud)
所以在这里,
0 完全删除制表符,1酷似默认8,2酷似1然后3 是不同的4像是在使用1然后它增加到8默认值然后在8.之后增加.但为什么数字中的奇怪模式从0到8?我知道它应该从8开始,但是原因是什么?
str.expandtabs(n)不等于str.replace("\t", " " * n).
str.expandtabs(n)跟踪每一行上的当前光标位置,并将其找到的每个制表符替换为当前光标位置到下一个制表位的空格数.制表位被视为每个n字符.
这是标签工作方式的基础,并非特定于Python.有关制表位的详细说明,请参阅相关问题的答案.
string.expandtabs(n) 相当于:
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# instead of the tab character, append the
# number of spaces to the next tab stop
char = " " * (n - pos % n)
pos = 0
elif char == "\n":
pos = 0
else:
pos += 1
result += char
return result
Run Code Online (Sandbox Code Playgroud)
以及使用示例:
>>> input = "123\t12345\t1234\t1\n12\t1234\t123\t1"
>>> print(expandtabs(input, 10))
123 12345 1234 1
12 1234 123 1
Run Code Online (Sandbox Code Playgroud)
请注意每个制表符("\t")是如何被替换为导致它与下一个制表位对齐的空格数.在这种情况下,因为我提供了每10个字符就有一个制表位n=10.
| 归档时间: |
|
| 查看次数: |
3180 次 |
| 最近记录: |