1212
1313# global verbosity switch
1414import re
15- from io import StringIO
16- from math import ceil
17-
18- import numpy as np
1915
2016verbose_level = 0
2117
@@ -42,32 +38,28 @@ def table2string(table, out=None):
4238 table : list of lists of strings
4339 What is aimed to be printed
4440 out : None or stream
45- Where to print. If None -- will print and return string
41+ Where to print. If None, return string
4642
4743 Returns
4844 -------
4945 string if out was None
5046 """
5147
52- print2string = out is None
53- if print2string :
54- out = StringIO ()
55-
5648 # equalize number of elements in each row
5749 nelements_max = len (table ) and max (len (x ) for x in table )
5850
51+ table = [row + ['' ] * (nelements_max - len (row )) for row in table ]
5952 for i , table_ in enumerate (table ):
6053 table [i ] += ['' ] * (nelements_max - len (table_ ))
6154
62- # figure out lengths within each column
63- atable = np .asarray (table )
6455 # eat whole entry while computing width for @w (for wide)
6556 markup_strip = re .compile ('^@([lrc]|w.*)' )
66- col_width = [max (len (markup_strip .sub ('' , x )) for x in column ) for column in atable .T ]
67- string = ''
68- for i , table_ in enumerate (table ):
69- string_ = ''
70- for j , item in enumerate (table_ ):
57+ col_width = [max (len (markup_strip .sub ('' , x )) for x in column ) for column in zip (* table )]
58+ trans = str .maketrans ("lrcw" , "<>^^" )
59+ lines = []
60+ for row in table :
61+ line = []
62+ for item , width in zip (row , col_width ):
7163 item = str (item )
7264 if item .startswith ('@' ):
7365 align = item [1 ]
@@ -77,26 +69,14 @@ def table2string(table, out=None):
7769 else :
7870 align = 'c'
7971
80- nspacesl = max (ceil ((col_width [j ] - len (item )) / 2.0 ), 0 )
81- nspacesr = max (col_width [j ] - nspacesl - len (item ), 0 )
82-
83- if align in ('w' , 'c' ):
84- pass
85- elif align == 'l' :
86- nspacesl , nspacesr = 0 , nspacesl + nspacesr
87- elif align == 'r' :
88- nspacesl , nspacesr = nspacesl + nspacesr , 0
89- else :
90- raise RuntimeError (f'Should not get here with align={ align } ' )
91-
92- string_ += '%%%ds%%s%%%ds ' % (nspacesl , nspacesr ) % ('' , item , '' )
93- string += string_ .rstrip () + '\n '
94- out .write (string )
72+ line .append (f'{ item :{align .translate (trans )}{width }} ' )
73+ lines .append (' ' .join (line ).rstrip ())
9574
96- if print2string :
97- value = out .getvalue ()
98- out .close ()
99- return value
75+ ret = '\n ' .join (lines ) + '\n '
76+ if out is not None :
77+ out .write (ret )
78+ else :
79+ return ret
10080
10181
10282def ap (helplist , format_ , sep = ', ' ):
0 commit comments