zoukankan      html  css  js  c++  java
  • 分享一下,python如何让每段文字向两侧对齐

    学到了

    原问题:

    回答:

     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.
  • 相关阅读:
    回到顶部
    angularjs 复选框 单选框
    关于angularjs的ng-repeat指令
    JS字符串对象
    JS的控制语句与异常
    JS的运算符
    JS的引入方式和基础规范
    z-index及透明度opacity,利用overflow设置头像
    css的定位
    css的float属性及清除浮动
  • 原文地址:https://www.cnblogs.com/ranzhong/p/14011556.html
Copyright © 2011-2022 走看看