python - 如何用变量替换格式或 f 字符串中的填充宽度来填充数字?

标签 python

<分区>

我想用基于变量 width 值的填充来填充数字 i

>>> width = 5
>>> i = 1
>>> print(f'{i:width}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier
>>>
>>> print('{:width}'.format(i))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier

期望的输出:

1

最佳答案

你几乎成功了:

>>> width = 5
>>> i = 1
>>> print(f'{i:{width}}')
    1

关于python - 如何用变量替换格式或 f 字符串中的填充宽度来填充数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546981/

相关文章:

python - '无法在另一个循环运行时运行事件循环')RuntimeError websockets?

python - 如何将数组列表转换为 Spark 数据帧

python - 使用 ftplib 的 SFTP

python - 灰度图像颜色表

python - 嵌入 python

python - 使用 boto 将文件从 ec2 传输到 s3 时出错

Python,从 input() 中删除所需的引号

python - 在 python 中创建词汇表

python - 在对象的 __class__ 属性上设置属性

python - 如何使用不同的 python 版本获取 tox 来测试 "named"测试环境?