Python 的 .format 的多行参数

Multiline arguments to Python's .format

我希望能够像这样打印字符串:

text1 v1 text2 v3
      v2       v4

其中 vi 是变量。我试过这个:

"text1 {} text2 {}".format("v1\nv2", "v3\nv4")

但是,不出所料,这给出了输出

text1 v1
v2 text2 v3
v4

因为 format 的第一个参数中的换行符适用于整行。

有没有什么好的方法可以将多行参数传递给 format 而不会破坏整个格式化字符串?

你真的可以做到这一点

In [1]: print "text1 {} text2 {}\n      {}       {}".format("v1", "v3", "v2", "v4")
text1 v1 text2 v3
      v2       v4

In [2]: print "text1\t{}\ttext2\t{}\n\t{}\t{}".format("v1", "v3", "v2", "v4")
text1   v1  text2   v3
        v2          v4

\t表示tab,\n表示换行

pip install tabulate

Python 中的漂亮打印表格数据、库和命令行 效用。

from tabulate import tabulate
table =[["text1", "v1", "text2", "v3"],["", "v2", "", "v4"]]
print(tabulate(table))

"table" 是父列表,它的元素将是要打印的 table 的行。