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

如何格式化Python列表,实现美观的字符串拼接输出?

Python列表输出格式优化:处理Decimal/日期类型并实现前缀对齐

问题场景

你有多个存储在data变量中的列表,当前拼接字符串的输出格式不符合预期:

  • 当前代码:
check_str = 'data is there'
print(check_str + '|' + ','.join(str(v) for v in data)) 
  • 实际输出(格式混乱,未解析Decimal和日期类型,多行无对齐):
data is there|0 rows returned
data is there|(Decimal('1456'),datetime.date(2022, 9, 15))(Decimal('156'),datetime.date(2012, 10, 15))
data is there|0 rows returned
data is there|0 rows returned
data is there|(Decimal('1256'),datetime.date(2112, 9, 15)), (Decimal('56'),datetime.date(2012, 10, 25)), (Decimal('561'),datetime.date(2012, 10, 25))
  • 期望输出(解析Decimal为数字、日期为标准格式,多行对齐前缀):
data is there|0 rows returned
data is there|1456|2022-09-15
             |156|2022-10-15
data is there|0 rows returned
data is there|0 rows returned
data is there|1256|2112-09-15
             |56|2012-10-25
             |561|2012-10-25

解决方案代码

from decimal import Decimal
import datetime

check_str = 'data is there'
prefix_length = len(check_str)

# 假设data是包含多个子列表的大列表,示例结构如下
data = [
    ['0 rows returned'],
    [(Decimal('1456'), datetime.date(2022, 9, 15)), (Decimal('156'), datetime.date(2012, 10, 15))],
    ['0 rows returned'],
    ['0 rows returned'],
    [(Decimal('1256'), datetime.date(2112, 9, 15)), (Decimal('56'), datetime.date(2012, 10, 25)), (Decimal('561'), datetime.date(2012, 10, 25))]
]

for item_list in data:
    # 处理单条字符串的情况(如0 rows returned)
    if len(item_list) == 1 and isinstance(item_list[0], str):
        print(f"{check_str}|{item_list[0]}")
        continue
    
    # 处理包含(Decimal, date)元组的列表
    for idx, (dec_val, date_val) in enumerate(item_list):
        # 第一行用原前缀,后续行用空格对齐
        current_prefix = check_str if idx == 0 else ' ' * prefix_length
        # 转换Decimal为普通数字字符串,日期转为YYYY-MM-DD格式
        dec_str = str(dec_val)
        date_str = date_val.strftime('%Y-%m-%d')
        print(f"{current_prefix}|{dec_str}|{date_str}")

代码说明

  1. 前缀对齐处理:预计算check_str的长度,后续多行输出时用同等长度的空格填充前缀,实现对齐效果。
  2. 类型解析与转换:
    • Decimal类型直接转为字符串即可得到纯数字格式。
    • 使用date.strftime('%Y-%m-%d')将datetime.date对象转为标准日期字符串。
  3. 分支逻辑:区分两种输出场景(单条字符串、多组元组),分别处理输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:50:39