text wrapping help

Ryan K ryankaskel at gmail.com
Wed Feb 28 19:58:25 EST 2007


Okay, I was a little vague in my last post...the matrix is like a
Wheel of Fortune board and it knows nothing about newlines. After 24
characters it spills over onto the next line. Here is what I came up
with:

<pre>
## Wrap Text

def wrap_text(in_str, chars_line):
    """ wrap text """
    spaces = 0
    new_str = ""
    tmp_str = ""
    while True:
        tmp_str = in_str[:chars_line]
        if tmp_str[chars_line-1].isspace():
            new_str += tmp_str
        else:
            spaces = 0
            for ch in reversed(tmp_str):
                if ch.isspace():
                    break
                spaces += 1
            tmp_str = tmp_str[:chars_line-spaces]
            tmp_str += " " * spaces
            new_str += tmp_str
            in_str = in_str[chars_line-spaces:]
        if len(in_str) <= chars_line:
            new_str += " " + in_str
            break
    return new_str


if __name__ == '__main__':

    sample_text = """Personal firewall software may warn about the
connection IDLE makes to its subprocess using this computer's internal
loopback interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet."""
    print wrap_text(sample_text, 24)

</pre>

It doesn't even run but when I go through it interactively it seems
okay. Once again, any help is appreciated.


On Feb 28, 7:06 pm, "Ryan K" <ryankas... at gmail.com> wrote:
> I'm trying to text wrap a string but not using the textwrap module. I
> have 24x9 "matrix"  and the string needs to be text wrapped according
> to those dimensions. Is there a known algorithm for this? Maybe some
> kind of regular expression? I'm having difficulty programming the
> algorithm. Thanks,
> Ryan




More information about the Python-list mailing list