【问题标题】:tabulate showing "\n" while printing打印时显示“\n”的表格
【发布时间】:2019-06-12 19:36:33
【问题描述】:

我想在终端上打印一张表格,为此我使用tabulate 包,但我有额外的返回战车'\n'。如何删除它们?

import pandas as pd
from tabulate import tabulate
df = pd.DataFrame({'schools' : ['Harvard', 'MIT', 'UCal', 'Cornell'],
                   'Faculty' : ['CS', 'Psychology', 'Biology', 'BioInformatics']})
print(tabulate(df,headers='keys',tablefmt='psql'))

结果

('+----+-----------+----------------+\n'
 '|    | schools   | Faculty        |\n'
 '|----+-----------+----------------|\n'
 '|  0 | Harvard   | CS             |\n'
 '|  1 | MIT       | Psychology     |\n'
 '|  2 | UCal      | Biology        |\n'
 '|  3 | Cornell   | BioInformatics |\n'
 '+----+-----------+----------------+')

【问题讨论】:

  • 当我在我的终端中尝试你的例子时,它很好。你是如何使用你的脚本的?它是否在文件 script.py 中,然后使用如下命令运行:python3 script.py ?
  • 是的,我正在使用脚本'poetry run python file.py'
  • 你在用python2吗?

标签: python python-3.7 tabulate


【解决方案1】:

看起来您实际上并没有打印字符串,而是包含该字符串的其他内容。在我的终端中,如果我使用你的代码,它就可以工作:

jvaubien@ml18-pc03 ~/Downloads> python3 test.py
+----+----------------+-----------+
|    | Faculty        | schools   |
|----+----------------+-----------|
|  0 | CS             | Harvard   |
|  1 | Psychology     | MIT       |
|  2 | Biology        | UCal      |
|  3 | BioInformatics | Cornell   |
+----+----------------+-----------+

使用包含您的代码示例的 test.py。

但如果我这样做:

import pandas as pd
from tabulate import tabulate
df = pd.DataFrame({'schools' : ['Harvard', 'MIT', 'UCal', 'Cornell'],
                   'Faculty' : ['CS', 'Psychology', 'Biology', 'BioInformatics']})
x = tabulate(df, headers='keys', tablefmt='psql')
print((x,))

得到与你相同的结果括号和\n。

您确定要打印字符串而不是其他内容吗?如果只打印字符串,则字符串周围会有括号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多