There is no way to do that I know of that's build in. You can however try to solve it yourself:
One possible (not that great looking) algorithm:
- split text into lines
- find longest line
- for all other lines:
- find first space, and add another space
- if still not long enough, move to next not yet elongated space
This could look like so:
def justify_text(text):
# split text into lines and find longest
lines = [line.strip() for line in text.split("\n")]
ll = len(max(lines, key=len))
# iterate lines
for i, l in enumerate(lines):
# remember last elongates space
pos_space = 0
# do for all lines but the last one
while len(l) < ll and (i != len(lines)-1):
# print(l) # uncomment to see stages of refining
pos_space = l.find(" ", pos_space)
if pos_space == -1:
# start over from beginning
pos_space = l.find(" ", 0)
if pos_space == -1:
# no space inside the line, can't do anything about it
# we break to avoid endless loop
break
# splice in a space and increase next search position
l = l[:pos_space] + " " + l[pos_space:]
pos_space += 2
# store changed line
lines[i] = l
return '\n'.join(lines)
t = """Lorem ipsum dolor sit amet, consectetur adipiscing more text
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit."""
print(justify_text(t))
and produces:
Lorem ipsum dolor sit amet, consectetur adipiscing more text
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit.
To get closer to what your text looks like you would have to find the space to elongate from alternatingly searching from both sides of the line.
If you do not start from a already line-split text you can do a pre-step (although using the linked algo from codereview is more efficient in that case):
t = """Lorem ipsum dolor sit amet, consectetur adipiscing more text elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit."""
def prep_text(text, no_longer_then=50):
words = text.split(" ")
result = [[]]
for w in words:
if sum(len(part) for part in result[-1]) + len(w) > no_longer_then:
result.append([w])
else:
result[-1].append(w)
print(result)
return '\n'.join(' '.join(inner) for inner in result)
prepped = prep_text(t)
print(prepped)
Outputs:
# 1 2 3 4 5
# 345678901234567890123456789012345678901234567890
Lorem ipsum dolor sit amet, consectetur adipiscing
more text elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit.