Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Text Formatting by mildm
def text_formatting(text: str, width: int, style: str) -> str:
def alig(ww,n,a):
if a=="l": return " ".join(ww)
if a=="r": return (" "*n)+(" ".join(ww))
if a=="c": return (" "*(n//2))+(" ".join(ww))
rv=ww[0]
g=len(ww)-1
for w in ww[1:]:
rv+=" "*(1+(n+g-1)//g)+w
n-=(n+g-1)//g
g-=1
return rv
text+=" "
ww=[]
while " " in text:
ww.append(text[:text.index(" ")])
text=text[text.index(" ")+1:]
li=[]
l=0
rv=""
for w in ww:
if l+len(w)>width:
rv+=alig(li,width-l+1,style)+"\n"
l=0
li=[]
l+=len(w)+1
li.append(w)
rv+=alig(li,width-l+1,"l" if style=="j" else style)
return rv
Oct. 21, 2023