如何在python中调整文本右对齐

2024-10-01 02:36:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多长度的虚拟文本

sample_text = """Nunc tempus metus sem, at posuere nulla volutpat viverra. Sed nec nisl imperdiet, egestas ex et, sodales libero. Suspendisse egestas id dui at aliquet. Nulla a justo neque. Pellentesque non urna iaculis, maximus dolor at, pellentesque eros. Duis mi velit, ornare eu mollis sed, congue eget nisl. Ut suscipit, elit eu mattis vehicula, justo quam vulputate urna, nec tempor augue ligula sed nisl. Phasellus vel augue eu nibh sodales pretium ornare vel felis.Vivamus vitae suscipit orci. """

我正在寻找一种方法来证明文本的合理性,比如right对齐。检查了text wrap文档,但只剩下默认值

import textwrap
wrapper = textwrap.TextWrapper(width=50)
dedented_text = textwrap.dedent(text=sample_text)
print(wrapper.fill(text=dedented_text))

文本换行还提供了许多功能,如缩写、缩进等

找到了另一种解释文本的方法

str.ljust(s, width[, fillchar])
str.rjust(s, width[, fillchar])
str.center(s, width[, fillchar])

但上述功能仅在文本长度小于宽度时才起作用

是否有任何类似上述的功能或方法来证明文本的合理性


Tags: sample方法text文本功能widthatnec
1条回答
网友
1楼 · 发布于 2024-10-01 02:36:16

过于简单的做法是:

import re
wrapper = textwrap.TextWrapper(width=50)
dedented_text = textwrap.dedent(text=sample_text)

txt = wrapper.fill(text=dedented_text)
def justify(txt:str, width:int) -> str:
    prev_txt = txt
    while((l:=width-len(txt))>0):
        txt = re.sub(r"(\s+)", r"\1 ", txt, count=l)
        if(txt == prev_txt): break
    return txt.rjust(width)

for l in txt.splitlines():
    print(justify(l, 50))

很少注意:

(1)对齐关注点行,而不是字符串中的行-因此您应该逐行对齐文本。这里没有批量方法

(2)你总是通过扩展空间来证明自己的合理性-这只是你自己的决定,你选择了哪些空间以及如何扩展它们-我发现网上所有的例子都不同,只是它们使用的扩展空间的方法不同

输出:

Nunc  tempus  metus sem, at posuere nulla volutpat
viverra.  Sed  nec  nisl imperdiet, egestas ex et,
sodales  libero.  Suspendisse  egestas  id  dui at
aliquet.  Nulla  a  justo  neque. Pellentesque non
urna iaculis, maximus dolor at, pellentesque eros.
Duis  mi  velit, ornare eu mollis sed, congue eget
nisl.  Ut suscipit, elit eu mattis vehicula, justo
quam  vulputate  urna, nec tempor augue ligula sed
nisl.  Phasellus vel augue eu nibh sodales pretium
ornare  vel  felis.Vivamus  vitae  suscipit  orci.

相关问题 更多 >