首页 > 技术文章 > 分享一下,python如何让每段文字向两侧对齐

ranzhong 原文

学到了

原问题:

回答:

 1 def justify_text(text):
 2     # split text into lines and find longest
 3     lines = [line.strip() for line in text.split("
")]
 4     ll = len(max(lines, key=len))
 5 
 6     # iterate lines
 7     for i, l in enumerate(lines):
 8         # remember last elongates space
 9         pos_space = 0
10         # do for all lines but the last one
11         while len(l) < ll and (i != len(lines)-1):
12             # print(l) # uncomment to see stages of refining
13             pos_space = l.find(" ", pos_space)
14             if pos_space == -1:
15                 # start over from beginning
16                 pos_space = l.find(" ", 0)
17                 if pos_space == -1:
18                     # no space inside the line, can't do anything about it
19                     # we break to avoid endless loop
20                     break
21             # splice in a space and increase next search position
22             l = l[:pos_space] + " " + l[pos_space:]
23             pos_space += 2
24         # store changed line
25         lines[i] = l
26 
27     return '
'.join(lines)
28 
29 t = """Lorem ipsum dolor sit amet, consectetur adipiscing more text
30 elit, sed do eiusmod tempor incididunt ut labore 
31 et dolore magna aliqua. Ut enim ad minim veniam, 
32 quis nostrud exercitation ullamco laboris nisi ut 
33 aliquip ex ea commodo consequat. Duis aute irure  
34 dolor in reprehenderit."""
35 
36 print(justify_text(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.

推荐阅读