Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Text Formatting by kurosawa4434
def text_formatting(text: str, width: int, style: str) -> str:
def make_row(text):
rest = text.split()
row = []
while rest:
word = rest.pop(0)
if len(' '.join(row + [word])) > width:
yield ' '.join(row), False
row.clear()
row.append(word)
yield ' '.join(row), True
def justify(row, width):
q, r = divmod(width-len(row), row.count(' '))
return ''.join(' '*(1+q+(i <= r))*(i > 0)+w for i, w in enumerate(row.split(' ')))
result = []
fn = {'r': str.rjust, 'l': str.ljust, 'c': str.center, 'j': justify}
for row, last in make_row(text):
if style == 'j' and last:
style = 'l'
result.append(fn[style](row, width).rstrip())
return '\n'.join(result)
if __name__ == '__main__':
LINE = ('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure '
'harum suscipit aperiam aliquam ad, perferendis ex molestias '
'reiciendis accusantium quos, tempore sunt quod veniam, eveniet '
'et necessitatibus mollitia. Quasi, culpa.')
print('Example:')
print(text_formatting(LINE, 38, 'l'))
assert text_formatting(LINE, 38, 'l') == \
'''Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Iure
harum suscipit aperiam aliquam ad,
perferendis ex molestias reiciendis
accusantium quos, tempore sunt quod
veniam, eveniet et necessitatibus
mollitia. Quasi, culpa.''', 'Left 38'
assert text_formatting(LINE, 30, 'c') == \
''' Lorem ipsum dolor sit amet,
consectetur adipisicing elit.
Iure harum suscipit aperiam
aliquam ad, perferendis ex
molestias reiciendis
accusantium quos, tempore sunt
quod veniam, eveniet et
necessitatibus mollitia.
Quasi, culpa.''', 'Center 30'
assert text_formatting(LINE, 50, 'r') == \
''' Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Iure harum suscipit aperiam
aliquam ad, perferendis ex molestias reiciendis
accusantium quos, tempore sunt quod veniam,
eveniet et necessitatibus mollitia. Quasi, culpa.''', 'Right 50'
assert text_formatting(LINE, 45, 'j') == \
'''Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Iure harum suscipit aperiam
aliquam ad, perferendis ex molestias
reiciendis accusantium quos, tempore sunt
quod veniam, eveniet et necessitatibus
mollitia. Quasi, culpa.''', 'Justify 45'
May 13, 2019
Comments: