Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Text Formatting by lxf42
from textwrap import wrap, fill
def text_formatting(text: str, width: int, style: str) -> str:
match style:
case 'l':
return fill(text, width)
case 'c':
return '\n'.join(f'{line:^{width}}'.rstrip() for line in wrap(text, width))
case 'r':
return '\n'.join(x.rjust(width) for x in wrap(text, width))
case 'j':
text = fill(text, width).splitlines()
for i in range(len(text)-1):
line = text[i]
nb_spaces = line.count(' ')
to_add = width - len(line)
long_spaces = ' ' * (to_add//nb_spaces + 1)
line = line.replace(' ', long_spaces)
line = line.replace(long_spaces, long_spaces + ' ', to_add % nb_spaces)
text[i] = line
return '\n'.join(text)
return ''
May 11, 2022
Comments: