You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用tabulate包生成表格右列数据过长显示异常如何解决

Python tabulate包长列内容显示异常解决方案
  • 方案1:使用maxcolwidths参数直接限制列宽
    这是最简单的处理方式,调用tabulate时直接指定各列的最大宽度,超出宽度的内容会自动换行,避免表格整体变形:
from tabulate import tabulate

# 此处替换为你自己的表格数据
data = [
    ["TRILOSTANE", "Plaque, Amyloid , Eye Pain , Sacroiliitis , Cognitive Dysfunction , Drug-Related Side Effects and Adverse Reactions , Non-alcoholic Fatty Liver Disease , OVARIAN DYSGENESIS 1 , Abortion, Spontaneous , Squamous Cell Carcinoma of Head and Neck , Acromegaly , ACTH Syndrome, Ectopic , Adenocarcinoma , Adenoma , Adrenal Cortex Diseases , Adrenal Gland Neoplasms , Adrenal Hyperplasia, Congenital , Alcoholism , Alzheimer Disease , Amenorrhea , Amnesia , Amyloidosis , Angina Pectoris , Angina, Unstable , Hypoxia , Anuria , Anxiety Disorders , Aortic Stenosis, Subvalvular , Arrhythmias, Cardiac , Arterial Occlusive Diseases , Asphyxia Neonatorum , Asthma , Astrocytoma , Atrial Fibrillation , Autistic Disorder , Mental Disorders , Behcet Syndrome , Bipolar Disorder , Urinary Bladder Neoplasms , Body Weight , Bone Diseases, Metabolic , Bone Neoplasms , Bradycardia , Brain Diseases , Brain Edema , Breast Neoplasms , Burns , Cachexia , Calcinosis , Carcinoma , Carcinoma, Non-Small-Cell Lung , Carcinoma, Renal Cell"]
]

# 可按需调整各列的最大宽度数值,示例中第一列最大宽30,第二列最大宽80
print(tabulate(data, tablefmt="grid", maxcolwidths=[30, 80]))
  • 方案2:配合textwrap模块自定义换行规则
    如果需要更灵活的换行控制,可以提前用textwrap对长文本做拆分处理,再传入tabulate生成表格:
from tabulate import tabulate
import textwrap

# 对长文本列做换行处理,每行最多80个字符,宽度可自定义
wrapped_long_col = textwrap.fill(data[0][1], width=80)
processed_data = [[data[0][0], wrapped_long_col]]

print(tabulate(processed_data, tablefmt="grid"))
  • 方案3:输出到文件避免终端截断
    如果需要保留完整长行不换行,可以把生成的表格输出到markdown、html等格式的文件中,不会受到终端宽度的限制:
from tabulate import tabulate

with open("output_table.md", "w", encoding="utf-8") as f:
    f.write(tabulate(data, tablefmt="pipe"))

内容的提问来源于stack exchange,提问作者quik1399

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:27:01