Skip to content

Instantly share code, notes, and snippets.

@miebach
Created May 13, 2012 18:24
Show Gist options
  • Save miebach/2689618 to your computer and use it in GitHub Desktop.
Save miebach/2689618 to your computer and use it in GitHub Desktop.
Aligns a list with spaces.
def tabbed_vector(v,tabs,DELIM=", ",LEFT="(",RIGHT="),"):
"""
Adjusts left or right with spaces and inserts commas.
>>> tabbed_vector([1,2],[2,2])
'(1 , 2 ),'
>>> tabbed_vector([1,2],[4,4])
'(1 , 2 ),'
>>> tabbed_vector([1,2],[4,-4])
'(1 , 2),'
>>> tabbed_vector(['abc',2],[5,-4])
"('abc', 2),"
Unicode strings take more space than old strings:
>>> tabbed_vector([u'abcdef',7],[9,-4])
"(u'abcdef', 7),"
If columns don't fit, an exception is raised:
>>> tabbed_vector(['abc'],[1])
Traceback (most recent call last):
...
Exception: Tab for column 0 is too small by 4 chars.
>>>
"""
SPACES=" "
i = 0
buf = []
for e in v:
t = tabs[i]
r = repr(e)
if len(r) > abs(t):
raise Exception("Tab for column %s is too small by %s chars." % (i,len(r) - abs(t)))
if t < 0:
el = (("%s%s" % (SPACES,r))[t:])
else:
el = (("%s%s" % (r,SPACES))[:t])
buf.append(el)
i = i + 1
return "%s%s%s" % (LEFT,DELIM.join(buf),RIGHT)
# Example usage:
def tab_matrix(m,tabs):
"""
>>> tab_matrix([["Apples",6],["Oranges",7],["Plums",300]],[9,-3])
['Apples' | 6]
['Oranges' | 7]
['Plums' | 300]
"""
for v in m:
print tabbed_vector(v,tabs,DELIM=" | ",LEFT="[",RIGHT="]")
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment