12
12
13
13
# global verbosity switch
14
14
import re
15
- from io import StringIO
16
- from math import ceil
17
-
18
- import numpy as np
19
15
20
16
verbose_level = 0
21
17
@@ -42,32 +38,28 @@ def table2string(table, out=None):
42
38
table : list of lists of strings
43
39
What is aimed to be printed
44
40
out : None or stream
45
- Where to print. If None -- will print and return string
41
+ Where to print. If None, return string
46
42
47
43
Returns
48
44
-------
49
45
string if out was None
50
46
"""
51
47
52
- print2string = out is None
53
- if print2string :
54
- out = StringIO ()
55
-
56
48
# equalize number of elements in each row
57
49
nelements_max = len (table ) and max (len (x ) for x in table )
58
50
51
+ table = [row + ['' ] * (nelements_max - len (row )) for row in table ]
59
52
for i , table_ in enumerate (table ):
60
53
table [i ] += ['' ] * (nelements_max - len (table_ ))
61
54
62
- # figure out lengths within each column
63
- atable = np .asarray (table )
64
55
# eat whole entry while computing width for @w (for wide)
65
56
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 ):
71
63
item = str (item )
72
64
if item .startswith ('@' ):
73
65
align = item [1 ]
@@ -77,26 +69,14 @@ def table2string(table, out=None):
77
69
else :
78
70
align = 'c'
79
71
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 ())
95
74
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
100
80
101
81
102
82
def ap (helplist , format_ , sep = ', ' ):
0 commit comments