Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Left because center justification wasn't right. solution in Clear category for Text Formatting by veky
def text_formatting(text, width, style):
def lines(words):
line = next(words)
for word in words:
old_line = line
line += ' ' + word
if len(line) > width:
yield old_line, False
line = word
yield line, True
def interleave(line):
words = line.split()
n = len(words) - 1
q, r = divmod(width - len(line), n)
for word, space in zip(words, [' '*(q+1)]*r + [' '*q]*(n-r)):
yield word + ' ' + space
yield words[~0]
def align(line):
if style == 'l': return line
elif style == 'r': return line.rjust(width)
elif style == 'c': return format(line, f'^{width}').rstrip()
elif style == 'j': return ''.join(interleave(line))
def aligned():
for line, last in lines(iter(text.split())):
if last and style == 'j': yield line
else: yield align(line)
return '\n'.join(aligned())
May 15, 2019
Comments: