python - 如何在 str.format() 中使用宽度和精度变量?

标签 python python-3.x string-formatting

如何在 str.format() 规范中使用变量来表示宽度和精度?

(我使用的是 Python 3。)

这工作正常:

print('    {:<127.127}  {:<}'.format(value[1], value[0]))

但这会产生错误:

SHOWLEN = 127
print('    {:<SHOWLEN.SHOWLEN}  {:<}'.format(value[1], value[0]))

具体来说,我得到:

Traceback (most recent call last):

  File "C:\Users\Dave\Desktop\index\treeIndex.py", line 101, in <module>
    treeIndex(sys.argv[1])

  File "C:\Users\Dave\Desktop\index\treeIndex.py", line 96, in treeIndex
    print('    {:<SHOWLEN.SHOWLEN}  {:<}'.format(value[1], value[0]))

ValueError: Invalid format specifier

如何使用变量来表示精度和宽度?

最佳答案

SHOLEN 括在括号中

"{varname:<{SHOWLEN}.{SHOWLEN}f}".format(varname=34.54, SHOWLEN=8)

这从 Format String Syntax 的以下引用中可以明显看出文档:

A format_spec field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

关于python - 如何在 str.format() 中使用宽度和精度变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589980/

相关文章:

python-3.x - PyTorch - Torchvision - BrokenPipeError : [Errno 32] Broken pipe

Python numpy 科学记数法限制小数位数

c# - .NET 字符串格式 - 小数点左边的 # 是什么意思?

python - 使用 map(function, list) 来转换对象而不返回列表是否合适?

python - 通过 systemd 运行 Python 脚本无法加载模块

python - 我的 '==' 运算符(operator)不工作

swift - 在小数点分隔符前后都打印 Double 和两位数字

python - 使用元类实现工厂设计模式

python - 从只有登录后才可用的网站获取受限数据

python - 生成自定义 pyunit 报告