ActiveState Code

Recipe 286129: Word wrapping generator


A simple generator function to return an input string in fragments, each broken at spaces in the text.

Python
 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
32
33
34
35
36
37
38
39
40
41
strings = [
"""Deep Thoughts
   - by Jack Handy
   ===============""",
"It takes a big man to cry, but it takes a bigger man to laugh at that man.",
"When you're riding in a time machine way far into the future, don't stick your elbow out the window, or it'll turn into a fossil.",
"I wish I had a Kryptonite cross, because then you could keep both Dracula AND Superman away.",
"I don't think I'm alone when I say I'd like to see more and more planets fall under the ruthless domination of our solar system.",
"I hope if dogs ever take over the world, and they chose a king, they don't just go by size, because I bet there are some Chihuahuas with some good ideas.",
"The face of a child can say it all, especially the mouth part of the face."
]

def wordWrap(s,length):
    offset = 0
    while offset+length < len(s):
        if s[offset] in ' \n':
            offset += 1
            continue
        
        endOfLine = s[offset:offset+length].find('\n')
        if endOfLine < 0:
            endOfLine = s[offset:offset+length].rfind(' ')
        
        if endOfLine < 0:
            endOfLine = length
            newOffset = offset + endOfLine
        else:
            newOffset = offset + endOfLine + 1
        
        yield s[offset:offset+endOfLine].rstrip()
        
        offset = newOffset
    
    if offset < len(s):
        yield s[offset:].strip()
        

for s in strings:
    for l in wordWrap(s,20):
        print l
    print

Comments

  1. 1. At 9:58 a.m. on 29 jun 2004, Paul McGuire (the author) said:

    Update. Updated to add attribution of quotes, and add support for embedded newlines.

  2. 2. At noon on 30 may 2008, Paul McGuire (the author) said:

    Never mind! (a la Emily Letella). Or just use the textwrap module!

Sign in to comment