Python expandtabs字符串操作

2024-05-20 07:16:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

string.expandtabs(s[, tabsize])

Expand tabs in a string replacing them by one or more spaces, depending on the current column and the given tab size. The column number is reset to zero after each newline occurring in the string. This doesn’t understand other non-printing characters or escape sequences. The tab size defaults to 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点开始,但原因是什么?在


Tags: orthetoin命令sizestringis
2条回答

expandtabs方法用空格字符替换{},直到下一个tabsize参数的倍数,即下一个制表符位置。在

例如,str.expandtabs(5)

将索引'\tswing'向前移动,直到字符串'\ts7'被替换为whitestring'。所以你看到10-7=3个空格。 (**括号内数字为索引编号**)

第二组。str.expandtabs(4)

'this(4)is(7)\t字符串'here'\t'将替换到index=8。所以你只看到一个空格

^{}不等于^{}。在

str.expandtabs(n)跟踪每行上的当前光标位置,并将找到的每个制表符替换为从当前光标位置到下一个制表位的空格数。制表位被视为每n个字符。在

这是选项卡工作方式的基础,而不是Python特有的。有关制表位的详细说明,请参见this answer to a related question。在

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

以及使用示例:

^{pr2}$

请注意,每个制表符("\t")是如何被替换为空格数的,从而使其与下一个制表位对齐。在本例中,因为我提供了n=10,所以每隔10个字符就有一个制表位。在

相关问题 更多 >