Python expandtabs字符串操作
我正在学习Python,并开始使用expandtabs
Python编写命令。这是文档中的正式定义:
string.expandtabs(s[, tabsize])
将字符串中的制表符扩展为一个或多个空格,具体取决于当前列和给定的制表符大小。在字符串中出现每个换行符后,列号将重置为零。这不了解其他非打印字符或转义序列。选项卡的大小默认为8。
因此,据我了解,制表符的默认大小为8,要增加该大小,我们可以使用其他值
因此,当我在外壳中尝试时,我尝试了以下输入-
>>> 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
所以在这里,
0
完全删除制表符,1
与默认值完全相同8
,- 但
2
完全像1
然后 3
是不同的- 然后
4
就像使用1
之后,它增加了,直到8
这是默认设置,然后8.But后增加为什么怪异图案的数字从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
并举例说明:
>>> input = "123\t12345\t1234\t1\n12\t1234\t123\t1" >>> print(expandtabs(input, 10)) 123 12345 1234 1 12 1234 123 1
请注意,每个制表符(
"\t"
)如何被替换为使其与下一个制表符对齐的空格数量。在这种情况下,因为我提供了,所以每10个字符都有一个制表位n=10
。