Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
textwrap, operator.methodcaller, str.replace with all 3 arguments solution in Clear category for Text Formatting by Phil15
from textwrap import wrap, fill
from operator import methodcaller
METHODS = {'l': 'ljust', 'c': 'center', 'r': 'rjust'}
def text_formatting(text: str, width: int, style: str) -> str:
if style == 'l': # These two lines are unnecessary but it's good to know.
return fill(text, width)
lines = wrap(text, width)
if style != 'j':
just = methodcaller(METHODS[style], width)
return '\n'.join(map(str.rstrip, map(just, lines)))
last = lines.pop() # We won't change the last line.
for i, line in enumerate(lines):
miss, spaces = width - len(line), line.count(' ')
if spaces: # To avoid ZeroDivisionError when dividing by "spaces".
div, mod = divmod(miss, spaces)
lines[i] = line.replace(' ', ' '*(div+1)).replace(' '*(div+1),
' '*(div+2), mod)
return '\n'.join(lines + [last])
April 25, 2019
Comments: