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.
  • 相关阅读:
    Gitlab 与 Git Windows 客户端一起使用的入门流程
    怎样把SEL放进NSArray里
    PerformSelector may cause a leak because its selector is unknown 解决方法
    drawRect
    记录常规越狱的判断方法
    网页 js
    UICollectionView 基础
    FMDB的简单使用
    图层的一些基本动画效果
    NSPredicate简单介绍
  • 原文地址:https://www.cnblogs.com/ranzhong/p/14011556.html
Copyright © 2011-2022 走看看