Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
split with regexp solution in Clear category for Text Formatting by tokyoamado
import re
from functools import reduce
from itertools import chain, repeat
def text_formatting(text: str, width: int, style: str) -> str:
splitter = re.compile(r'(?:^|(?<=\s)).{,' + str(width) + '}(?:(?=\s)|$)')
lines_org = [s for s in splitter.findall(text)]
lines = [line_formatting(s, width, style) for s in lines_org]
if style == 'j':
lines.pop()
lines.append(lines_org[-1])
return '\n'.join(lines)
def line_formatting(line: str, width: int, style: str) -> str:
if style == 'l':
return line
if style == 'c':
return line.center(width).rstrip()
if style == 'r':
return line.rjust(width)
if style == 'j':
words = line.split()
num_w = len(words)
if num_w <= 1:
return line
margin = width - sum(map(len, words))
p, m = divmod(margin, num_w - 1)
margins = chain(repeat(p + 1, m), repeat(p, num_w - 1 - m), [0])
return reduce(lambda s, w: s + w[0] + ''.ljust(w[1]), zip(words, margins), '')
May 15, 2019
Comments: