Skip to content

Instantly share code, notes, and snippets.

@lextoumbourou
Created April 25, 2012 04:34
Show Gist options
  • Save lextoumbourou/2486385 to your computer and use it in GitHub Desktop.
Save lextoumbourou/2486385 to your computer and use it in GitHub Desktop.
My version of the 13 characters per line problem described here: http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html (estimated 10 minutes, took me 30)
the_str = """Four score and seven years ago our fathers brought forth upon this \
continent a new nation, conceived in liberty and dedicated to the \
proposition that all men are created equal..."""
def word_wrap(the_str, chars_per_line):
'''
Returns formatted string based on number of characters per line
'''
iterator,space_pos,line_count = 0,0,0
output = the_str
# Go through the string's characters one at a time
while iterator < len(output):
# If we come across a space, we'll note where
if output[iterator] == ' ':
space_pos = iterator
# Once we get to the end of the line, we need to work out where to put the line break
if line_count == (chars_per_line-1):
# If we have found a space since the last line break insert
# then break the string in half at the space and put the break there
if space_pos > iterator-(chars_per_line-1):
output = output[:space_pos] + ' \n' + output[space_pos+1:]
# We're going to put our iterator back where the space was, plus one more
# to get in front of the line break
iterator = space_pos+1
# If we haven't found a space, then we'll just push it in the middle
# of the word, adding a hyphen
else:
output = output[:iterator] + '-\n' + output[iterator+1:]
# We're now working on a new line, start the counter again
line_count = 0
iterator += 1
line_count += 1
return output
if __name__ == '__main__':
print word_wrap(the_str, 13)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment