【问题标题】:Python expandtabs string operationPython expandtabs字符串操作
【发布时间】:2015-12-31 11:55:07
【问题描述】:

我正在学习 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 开始,但这是什么原因呢?

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    还有一个使用示例:

    >>> 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

    【讨论】:

    • 另见this question与您的解释相关。
    • 您能用更简单的方式解释一下吗?在我在问题中添加的情况下,我无法理解这将如何改变输出。
    • @WutWut:也许看看tab stop 是什么,这应该可以帮助您了解tab(制表符)的工作原理。
    • @WutWut 我在 Python 中添加了 expandtabs 函数的实现,以显示逻辑。
    【解决方案2】:

    expandtabs 方法将 \t 替换为空白字符,直到下一个 tabsize 参数的倍数,即下一个制表符位置。

    例如。取str.expandtabs(5)

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

    例如2。 str.expandtabs(4)

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

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多