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

简化Python中.format打印:如何将for循环嵌入print语句?

问题:将for循环嵌入print语句简化Python格式化打印

目标输出格式

-----------------------------
|             |             |
|             |      P      |
|             |      Y      |
|             |      T      |
|   PYTHON!   |      H      |
|             |      O      |
|             |      N      |
|             |      !      |
|             |             |
-----------------------------
|             |             |
|             |             |
|             |             |
|             |             |
|PYTHON!      |      PYTHON!|
|             |             |
|             |             |
|             |             |
|             |             |
-----------------------------

当前实现代码

rowBorder = '-' * 29
col = '|'
space = ' '
emptyColRow4 = (col + space * 13 + col + space * 13 + col + "\n") * 4
text = 'PYTHON!'
emptyRow = col+space*13+col+space*13+col

print(rowBorder)
print(emptyRow)
for l in text:
    if l != 'H':
        verticalLetter = '{}{}{}'.format(col + space*13 + col + space*6,l,space*6+col)
    else:
        verticalLetter = '{}{:^13}{}{}{}'.format(col,text, col + space*6,l,space*6+col)
    print(verticalLetter)
print(emptyRow)
print(rowBorder)
print(emptyColRow4,end='')
print('{}{:<13}{}{:>13}{}'.format(col,text,col,text,col))
print(emptyColRow4,end='')
print(rowBorder)

回答

当然可以,你可以用生成器表达式配合'\n'.join()把循环逻辑直接嵌入到print语句中,减少多次print调用,让代码更紧凑。同时推荐用f-string替代str.format(),可读性和简洁性更好。

修改后的代码如下:

rowBorder = '-' * 29
col = '|'
space = ' '
emptyColRow4 = f"{col}{' '*13}{col}{' '*13}{col}\n" * 4
text = 'PYTHON!'
emptyRow = f"{col}{' '*13}{col}{' '*13}{col}"

print(rowBorder)
print(emptyRow)
# 把for循环嵌入到print语句中
print('\n'.join(
    f"{col}{' '*13}{col}{' '*6}{l}{' '*6}{col}" if l != 'H' 
    else f"{col}{text:^13}{col}{' '*6}{l}{' '*6}{col}" 
    for l in text
))
print(emptyRow)
print(rowBorder)
print(emptyColRow4, end='')
# 修正原代码的转义问题,用f-string更直观
print(f"{col}{text:<13}{col}{text:>13}{col}")
print(emptyColRow4, end='')
print(rowBorder)

关键改动点:

  • 用'\n'.join(生成器表达式)把循环生成的每行内容拼接成一个字符串,一次性传给print
  • 全量替换为f-string,消除原代码中{:&lt;13}这类转义错误(正确写法是{:<13})
  • 统一字符串拼接方式,让代码逻辑更清晰

这样既实现了把循环嵌入print的需求,也优化了整体代码的可读性和简洁性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:00:23