2016-12-06 17 views
0

私はテーブル内のすべてのフィールドを整列する方法を知っている:テーブルの2番目と4番目の列だけを揃える方法は?

r=["this is my text of line1", 
    "and this was one more line", 
    "another line of text to display"] 

import re 
splitter = "\s+" 
columnstotal = [] 
for i in range(0,len(r)): 
    #remove splitter 
    columns = re.split(splitter, r[I]) 
    #keep splitter 
    columns = re.split('(' + splitter + ')', r[i]) 
    columnstotal.append(columns) 

と再び.format()を使用して列を表示する

が、どのように私は唯一の2列を揃える行います
列2を(右位置合わせ)+列4(左揃え)?

期待出力

 this is| my |text of line1 
    and this| was |one more line 
another line| of |text to display 
+0

を複数の入力データを与え、そしてあなたが出力として見たい正確な結果をしてください。 – jsbueno

+0

また、 'r 'の部分が必要な場合、Pythonの' r'の長さに 'for'という数字をつけないように気をつけてください:単に' rの部分のために '' – jsbueno

+0

@ jsbueno、私の質問を更新しました – Reman

答えて

1

あなたのスプリッタは3/4の部分に分かれていません...そして、あなたの例では、3列を示しています。
だから、あなたのスプリッタを修正し、で終わると仮定すると:

columnstotal = [['this is', 'my', 'text of line1'], 
       ['and this', 'was', 'one more line'], 
       ['another line', 'of', 'text to display']] 
width0 = max(len(d[0]) for d in s) 
width1 = max(len(d[1]) for d in s) 
for row in columnstotal: 
    print("{:>{width0}}| {:<{width1}} |{}".format(*row, width0=width0, width1=width1)) 

出力:

 this is| my |text of line1 
    and this| was |one more line 
another line| of |text to display 
+0

あなたの答えをありがとう。私のスプリッタは使用するものです。私は分割したいテキスト行を持っています。私の問題は、あなたの答えのように、列全体をどのように取得するのか分からないということです。あなたは "\ s +"の2回目と4回目にラインを分割する方法を知っていますか? Btwはあなたの答えの残りの部分をありがとう。 – Reman

関連する問題