Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 41 lines
 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

2 comments

Paul McGuire (author) 19 years, 9 months ago  # | flag

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

Paul McGuire (author) 15 years, 10 months ago  # | flag

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

Created by Paul McGuire on Thu, 10 Jun 2004 (PSF)
Python recipes (4591)
Paul McGuire's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks