2015-12-31 38 views
7

私はPythonについて学んでおり、Pythonでexpandtabsコマンドを取得しました。 これは、ドキュメント内の公式な定義です:Python expandtabs文字列操作

string.expandtabs(s[, tabsize]) 

は現在のカラムと与えられたタブのサイズに応じて、1つ以上のスペースでそれらを置き換える文字列内のタブを展開します。列番号は、文字列内に改行があるたびにゼロにリセットされます。これは他の非印字文字やエスケープシーケンスを理解しません。タブのサイズのデフォルト値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はまさに1のようなもので、その後、
  • 3
  • 異なっているし、再度41

を使用してのようなものであると、正確にデフォルト8よう

  • しかし2である、それは増加することが後にデフォルトである8まで増加してから8.Butの後に増加します。なぜ0〜8の数字の奇妙なパターンですか?私はそれが8から始めるはずですが、理由は何ですか?

  • 答えて

    7

    str.expandtabs(n)は、str.replace("\t", " " * n)と等価ではありません。

    str.expandtabs(n)は、各行の現在のカーソル位置を追跡し、見つかった各タブ文字を現在のカーソル位置から次のタブストップまでのスペース数で置き換えます。タブストップはすべてn文字であると解釈されます。

    これはタブの仕組みにとって基本的なことであり、Python固有のものではありません。タブストップの詳細については、this answer to a related questionを参照してください。

    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) 
         if char == "\n": 
          pos = 0 
         else: 
          pos += len(char) 
         result += char 
        return result 
    

    と使用の例:各タブ文字("\t")がラインにそれを原因とスペースの数に置き換えられているか

    >>> input = "123\t12345\t1234\t1\n12\t1234\t123\t1" 
    >>> print(expandtabs(input, 10)) 
    123  12345  1234  1 
    12  1234  123  1 
    

    は注意

    string.expandtabs(n)は同等です次のタブストップで上に移動します。この場合、n=10を入力したため、10文字ごとにタブストップがあります。

    +0

    説明に関連する[この質問](http://stackoverflow.com/questions/2656997/python-expand-tabs-length-calculation)も参照してください。 – Jens

    +0

    もっと簡単な方法で説明できますか?私は質問で追加したケースで出力がどのように変化するのか理解できません。 – WutWut

    +0

    @WutWut:[tab stop](https://en.wikipedia.org/wiki/Tab_stop)が何であるかを見てみましょう。それは 'tab'(tabulator)の仕組みを理解するのに役立つはずです。 – Jens

    2

    メソッドは、次のタブサイズ、つまり次のタブ位置まで、空白文字で置き換えます。

    たとえば、 take

    'this(5)is(7)\ tstring'ですので、インデックスが10になるまで\ tが空白に置き換えられ、後ろの文字列が前方に移動します。 10-7 = 3の空白が表示されます。 (**は角括弧内の数字はインデックス番号**です)

    eg2です。 str.expandtabs(4)

    'this(4)is(7)\ tstring' here '\ t'はindex = 8まで置換されます。 1つだけの空白が表示されます