Last active
December 16, 2015 05:49
-
-
Save alecmev/5387115 to your computer and use it in GitHub Desktop.
Text alignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def align(source, chars, mode): | |
source = list(source) | |
if len(source) == 0: | |
return '' | |
result = '' | |
lineBuffer = [source[0]] | |
lineLength = len(source[0]) | |
del source[0] | |
for word in source: | |
wordLength = len(word) | |
if lineLength + wordLength + 1 <= chars: | |
lineBuffer.append(word) | |
lineLength += wordLength + 1 | |
else: | |
result += alignLine(lineBuffer, lineLength, chars, mode) + '\n' | |
lineBuffer = [word] | |
lineLength = wordLength | |
return result + alignLine(lineBuffer, lineLength, chars, mode) | |
def alignLine(lineBuffer, lineLength, chars, mode): | |
spaces = chars - lineLength | |
if spaces <= 0 or mode == 'left': | |
return ' '.join(lineBuffer) | |
elif mode == 'center': | |
return ' ' * ((chars - lineLength) / 2) + ' '.join(lineBuffer) | |
elif mode == 'right': | |
return ' ' * (chars - lineLength) + ' '.join(lineBuffer) | |
else: | |
result = lineBuffer[0] | |
del lineBuffer[0] | |
wordCount = len(lineBuffer) | |
if wordCount == 0: | |
return result | |
freeCharCount = chars - lineLength | |
space = ' ' * (1 + freeCharCount / wordCount) | |
wideSpaceCount = freeCharCount % wordCount | |
for word in lineBuffer: | |
result += (' ' if wideSpaceCount > 0 else '') + space + word | |
wideSpaceCount -= 1 | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment