Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
textwrap, justify solution in Clear category for Text Formatting by Olpag
from textwrap import wrap
def text_formatting(text, width, style):
if len(text) <= width:
return text
lines = wrap(text, width)
if style == 'l':
return '\n'.join(lines)
if style == 'r':
return '\n'.join(line.rjust(width,' ') for line in lines)
if style == 'c':
return '\n'.join(line.center(width,' ').rstrip() for line in lines)
if style == 'j':
lines = [line.split(' ') for line in lines]
strings = []
for line in lines[:-1]:
blanks = len(line) -1
add_blanks = width - (sum(map(len, line)) + len(line) -1)
for i in range(add_blanks):
if i < blanks:
line[i] += ' '
else:
line[i%blanks] += ' '
strings += [' '.join(line)]
strings += [' '.join(lines[-1])]
return '\n'.join(strings)
Aug. 19, 2019