Revision history [back]

To solve this problem, you might want to write a custom print function.

The maximum line length can be an optional argument with a set default.

Below is one way to write such a custom print function that would apply not only to lists but to any Sage object, taking advantage of the spaces in its string representation to introduce line breaks.

The examples in the function's documentation show how to use it for a list and for a polynomial expression, but it would work with any other object.

def flowed(a, flow=72):
"""
Print this Sage object keeping line length below the specified bound

This will introduce line breaks where the string representation
of this object contains spaces.

INPUT:

- a -- a Sage object to be printed

- flow (optional, default: 72) -- bound for line length

EXAMPLES::

sage: a = range(32)
sage: flowed(a, flow=32)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31]
sage: flowed(a, flow=48)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31]
sage: p = taylor(log(1 + x), x, 0, 20)
sage: flowed(p)
-1/20*x^20 + 1/19*x^19 - 1/18*x^18 + 1/17*x^17 - 1/16*x^16 + 1/15*x^15 -
1/14*x^14 + 1/13*x^13 - 1/12*x^12 + 1/11*x^11 - 1/10*x^10 + 1/9*x^9 -
1/8*x^8 + 1/7*x^7 - 1/6*x^6 + 1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + x
"""
blocks = str(a).split()
s = blocks.pop(0)
c = len(s) + 1
while blocks:
b = blocks.pop(0)
p = len(b)
if c + p > flow:
print s
s = ''
c = 1
elif s:
s += ' '
c += 1
s += b
c += p
print s


Note that the documentation of the function can be accessed by typing

sage: flowed?