Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
spaces solution in Clear category for Text Formatting by karlian
from itertools import chain, repeat, zip_longest
from operator import concat
def split_lines(text, width):
start = end = 0
for word in map(len, text.split()):
if end+word > start+width:
yield text[start:end-1]
start = end
end += word+1
yield text[start:end-1]
def justify(line, width):
k, m = divmod(width-len(line), n := line.count(" "))
spaces = chain(repeat(" "*(k+1), m), repeat(" "*k, n-m), [""])
return " ".join(map(concat, line.split(), spaces))
def text_formatting(text: str, width: int, style: str) -> str:
lines = list(split_lines(text, width))
match style:
case "c":
def spaces(line): return " "*((width-len(line))//2)
lines = (spaces(line)+line for line in lines)
case "r":
def spaces(line): return " "*(width-len(line))
lines = (spaces(line)+line for line in lines)
case "j":
lines = chain((justify(line, width) for line in lines[:-1]), lines[-1:])
return "\n".join(lines)
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 18, 2022