Python 两个文本并排并具有精确的宽度

问题描述

我有一个练习,我有两个文本,“左”和“右”。
我需要制作一个函数,让它们并排并给出宽度作为参数,所有这些都使用 itertools 和 textwrap
这是我的代码

import textwrap
import itertools

def sidebyside(left,right,width=79):
    width = round((width+1)/2)
    leftwrapped = textwrap.wrap(left,width = width-1)
    
    for i in range(0,len(leftwrapped)):
        leftwrapped[i] = leftwrapped[i].ljust(width)
    
    rightwrapped = textwrap.wrap(right,len(rightwrapped)):
        rightwrapped[i] = rightwrapped[i].ljust(width)
    
    pipes = ["|"]*max(len(leftwrapped),len(rightwrapped))
    
    paragraph = itertools.zip_longest(leftwrapped,pipes,rightwrapped,fillvalue="".ljust(width))
    result = ""
    for a in paragraph:
        result = result + a[0] + a[1] + a[2] + "\n"
    
    return(result)

这是“左”和“右”的示例:

left = (
    "Lorem ipsum dolor sit amet,consectetur adipiscing elit. "
    "Sed non risus. "
    "Suspendisse lectus tortor,dignissim sit amet,"
    "adipiscing nec,utilisez sed sin dolor."
)

right = (
    "Morbi venenatis,felis nec pretium euismod,"
    "est mauris finibus risus,consectetur laoreet "
    "sem enim sed arcu. Maecenas sit amet eleifend sem. "
    "Nullam ac libero metus. Praesent ac finibus nulla,vitae molestie dolor."
    " Aliquam vestibulum viverra nisl,id porta mi viverra hendrerit."
    " Ut et porta augue,et convallis ante."
)

我的问题是我遇到了一些间距问题,即:对于第一行,对于给定的 20 长度,我有以下输出

'Lorem     |Morbi ven '

但我需要这个输出

'Lorem    |Morbi ven'

解决方法

找到了,我的round函数不好,只好做了两个宽度,第一个是除法的轮次,第二个是width - round(width/2)的结果。
说话便宜,代码更好:
从 itertools 导入 zip_longest 导入文本换行

def sidebyside(left,right,width=79):
    mid_width = (width - (1 - width%2)) // 2
    return "\n".join(
        f"{l.ljust(mid_width)}|{r.ljust(mid_width)}" 
        for l,r in zip_longest(
            *map(lambda t: textwrap.wrap("".join(t),mid_width),(left,right)),fillvalue=""
        )
    )

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...