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

如何使用程序化生成的f-string格式化嵌套列表输出

解决动态列数的列表格式化输出问题

你的问题出在只生成了格式化模板字符串,但没有把行数据代入模板执行格式化操作,直接打印模板当然只会输出字符串本身。以下是几种可行的解决方法:

方法一:用str.format()代入行数据

修改循环中的打印逻辑,将生成的模板通过format()方法传入当前行数据:

grid = [['parent', '', ''],
 ['child1', 'child2', '',],
 ['', 'grandchild1', 'grandchild2']]

f_string = ''
for col_index, col in enumerate(grid[0]):
    f_string += "{row[" + str(col_index) + "]:<20}"

for row in grid:
    # 把当前row传入模板,执行格式化
    print(f_string.format(row=row))

方法二:更简洁的模板生成方式

不需要手动拼接索引,直接根据列数生成通用占位符,再用解包语法传入行元素:

grid = [['parent', '', ''],
 ['child1', 'child2', '',],
 ['', 'grandchild1', 'grandchild2']]

# 定义列宽,根据列数生成格式化模板
col_width = 20
format_template = "{:<{width}}" * len(grid[0])

for row in grid:
    print(format_template.format(*row, width=col_width))

或者更直接的写法:

col_width = 20
format_template = "{:<20}" * len(grid[0])
for row in grid:
    print(format_template.format(*row))

不推荐的方法:使用eval

虽然可以通过eval将模板转换成f-string执行,但这种方式存在安全风险(如果行数据包含恶意代码可能被执行),所以不建议使用:

for row in grid:
    print(eval(f"f'{f_string}'"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:20:11