While experimenting Python’s string manipulation, I noticed that Python has tools for padding strings to certain lengths in order to center, left or right-justify text rendered in a monospaced font. The fourth popular text layout—text justified with both margins is notably not supported, as that traditionally involves variable-sized spaces.
While considering this problem, it occurred to me that padding strings with extra spaces between words would look clunky, but then I hit upon a solution—vowels. Whereas consonants provide much of the definition of words, vowels can be repeated or omitted with a minimal impact on readability. The following Python program justifies a column of text to the width of the first line, simply by duplicating or removing vowels (omitting capital vowels, as they often occur at the beginning of words, and it looks more awkward to chop them off).
# Justify text by adding and subtracting vowels import sys vowels = ['a', 'e', 'i', 'o', 'u'] lineLength = 0 for line in sys.stdin: line = line.strip() if lineLength == 0: lineLength = len(line) else: index = 0 while (len(line) < lineLength) or (len(line) > lineLength): if line[index] in vowels: if len(line) < lineLength: line = line[:index] + line[index] + line[index:] index = (index + 2) % len(line) elif len(line) > lineLength: line = line[:index] + line[index + 1:] else: index = (index + 1) % len(line) print line
As an example, take this one of Shakespeare’s sonnets.
Let me confess that we two must be twain, Although our undivided loves are one: So shall those blots that do with me remain, Without thy help, by me be borne alone. In our two loves there is but one respect, Though in our lives a separable spite, Which though it alter not love's sole effect, Yet doth it steal sweet hours from love's delight. I may not evermore acknowledge thee, Lest my bewailed guilt should do thee shame, Nor thou with public kindness honour me, Unless thou take that honour from thy name: But do not so, I love thee in such sort, As thou being mine, mine is thy good report.
When run through this Python script, each line is transformed, resulting in the following, nicely-justified text:
Let me confess that we two must be twain, Althoouugh oouur undivided loves are one: S shll thse blots that do with me remain, Wiithoout thy help, by me be borne alone. In ur two loves there is but one respect, Thoouugh iin our lives a separable spite, Whch thgh t alter not love's sole effect, Yt dth t stl swt hrs from love's delight. I maay noot eeveermoore acknowledge thee, Lst my bwiled guilt should do thee shame, Noor thou with public kindness honour me, Unlss thu take that honour from thy name: Buut do not so, I love thee in such sort, As th bing mine, mine is thy good report.
The comments are closed.