The following function returns a string representation of a 2D or 3D vector, which must be represented as a list
or tuple
containing 2 or 3 items:
>>> def str_vector(v):
... assert type(v) is list or type(v) is tuple,\
... 'argument to str_vector must be a list or tuple'
... assert len(v) in (2,3),\
... 'vector must be 2D or 3D in str_vector'
... unit_vectors = ['i','j','k']
... s = []
... for i, component in enumerate(v):
... s.append('{}{}'.format(component, unit_vectors[i])
... return '+'.join(s).replace('+-', '-')
replace('+-', '-')
here converts, for example, '4i+-3j'
into '4i-3j'
. For example,
>>> str_vector([4, -3])
'4i-3j'
>>> str_vector((4, -3, 2))
'4i-3j+2k'
>>> str_vector((4, -3, 2, -0.5))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in str_vector
AssertionError: vector must be 2D or 3D in str_vector