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

Python如何使用f-string或format为print输出开头添加4个空格

可行实现方法

方法1:直接在格式化字符串头部添加4个空格(最简单通用)

直接在原有第一个格式化字符串的开头加4个空格即可,修改后代码:

# format 写法
print('    {:<10}'.format('Constant'),'{:{width}.{prec}f}'.format(122, width=10, prec=3))

对应f-string等价写法:

# f-string 写法
width = 10
prec = 3
print(f"    {'Constant':<10} {122:{width}.{prec}f}")

方法2:通过占位符对齐生成前置空格

如果需要动态控制前置空格的数量,可以用空字符串占位的方式实现:

# 4个空格通过第一个占位符生成,调整占位符宽度即可修改前置空格数
print('{:<4}{:<10}'.format('', 'Constant'),'{:{width}.{prec}f}'.format(122, width=10, prec=3))

以上两种方法运行后都可以得到期望输出:

Constant     122.000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:45:03