Source

PythonDojo / WordWrap / wordwrap.py

#!/usr/bin/env python
# encoding: utf-8
"""
wordwrap.py

Created by Coding Dojo on 2013-03-13.
Copyright (c) 2013 PyUGAT. All rights reserved.
"""
import unittest
import re
WORD_RE = re.compile("[^ -]*.")


def wordwrap(string, columns):
    """Wrap input string at column."""
    output = []
    if len(string) < columns:
        return string
    words = WORD_RE.findall(string)
    remaining = columns
    for word in words:
        #if len(word) >= columns

        if len(word) < remaining:
            output.append(word)
        else:
            output.append("\n")
            remaining = columns
            output.append(word)
    return output

if __name__ == '__main__':
    unittest.main()