Python expandtabs字符串操作

时间:2015-12-31 11:55:07

标签: python python-2.7 python-3.x

我正在学习Python并使用Python中的expandtabs命令。 这是文档中的官方定义:

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

所以在这里,

  • 0完全删除制表符,
  • 1与默认8
  • 完全相同
  • 21完全相同,然后
  • 3不同
  • 然后再次4就像使用1
  • 一样

然后它增加到8这是默认值,然后在8.之后增加。但为什么数字中的奇怪模式从0到8?我知道它应该从8开始,但是原因是什么?

2 个答案:

答案 0 :(得分:8)

str.expandtabs(n)不等同于str.replace("\t", " " * n)

if (User.Identity.IsAuthenticated) { Response.Redirect("/Home"); } 跟踪每一行的当前光标位置,并将其找到的每个制表符替换为当前光标位置到下一个制表位的空格数。制表位将被视为每个str.expandtabs(n)个字符。

这是标签工作方式的基础,并非特定于Python。有关制表位的详细说明,请参阅this answer to a related question

n相当于:

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 )如何被替换为导致它与下一个制表位对齐的空格数。在这种情况下,每10个字符就有一个制表位,因为我提供了"\t"

答案 1 :(得分:2)

expandtabs方法用空白字符替换\t,直到下一个tabsize参数的倍数,即下一个标签位置。

例如。拿str.expandtabs(5)

'this(5)是(7)\ tstring'所以'\ t'被替换为空格,直到index = 10并且向后移动了后面的字符串。所以你看到10-7 = 3个空格。 (**括号内的数字是索引号**)

EG2。 str.expandtabs(4)

'this(4)is(7)\ tstring'the''t'替换直到index = 8。所以你只看到一个空格