如何安排打印元组中的内容

时间:2018-03-07 18:48:20

标签: python python-3.x

我正在尝试在元组中安排内容以适合特定的列布局。

示例布局:

PETER PAUL            MALE            100000
MARGARET              FEMALE          1000
MICHAEL JORDAN        MALE            1
AGNES                 FEMALE          200

但是当我遍历元组以打印内容时,它会输出:

PETER PAUL            MALE            100000
MARGARET             FEMALE            1000
MICHAEL JORDAN            MALE            1
AGNES            FEMALE            200

同样在我return row时,它只返回第一个tuple而不是全部。我正在返回它,因为我想在另一个函数中使用它。

这是下面的代码:

def text():
    rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200"))

    for row in rows:
       # print("          ".join(row))
        print("".join(row[0]), "".join("          "), "".join(row[1]), "".join("          "), "".join(row[2]))
        #return row

text()

我使用join方法,但我找不到ljust,我认为python3中不再提供@Entity @Table(name="MyTable") public class MyBlobWrapper{ @Id @Column(name = "id") // id of MyTable, same as MyClass private Long id; @Lob private byte[] bytes; } @Entity @Table(name="MyTable") public class MyClass{ @Id @Column(name = "id") private Long id; // other fields ..... }

2 个答案:

答案 0 :(得分:4)

使用Python的字符串.format()为每个元素赋予固定的宽度:

def text():
    rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200"))

    for row in rows:
        print('{:20} {:8} {}'.format(*row))

text()   

给你:

PETER PAUL           MALE     100000
MARGARET             FEMALE   1000
MICHAEL JORDAN       MALE     1
AGNES                FEMALE   200

format()命令通过将传递给它的参数替换为字符串中的每个{}来工作,在本例中为*row*具有将row内的三个值扩展为需要扩展的三个参数的效果。

要返回格式化文本,您需要先创建一个格式化行的列表,然后使用'\n'.join()将它们连接在一起,最后将换行:

def text():
    rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200"))

    data = []

    for row in rows:
        data.append('{:20} {:8} {}'.format(*row))

    return '\n'.join(data)

print(text())

这也可以使用Python“list comprehension”非常巧妙地完成,如下所示:

def text():
    rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200"))
    return '\n'.join('{:20} {:8} {}'.format(*row) for row in rows)

print(text())

答案 1 :(得分:0)

使用内联格式化:

def text():
    t = []
    rows = (("PETER PAUL", "MALE", "100000"),  ("MARGARET ", "FEMALE", "1000"), 
            ("MICHAEL JORDAN", "MALE", "1"),   ("AGNES", "FEMALE", "200"))

    for row in rows:
        t.append(f'{row[0]:<30}{row[1]:<10}{row[2]:<20}') 

    return t

for n in text():
    print(n) 

输出:

PETER PAUL                    MALE      100000              
MARGARET                      FEMALE    1000                
MICHAEL JORDAN                MALE      1                   
AGNES                         FEMALE    200    

格式:

如果您需要右键调整使用<20,则不需要

>20表示字符串,因为left-adjust是默认值。有关格式化语言结构的更多信息,请参阅链接。