gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:39:32 24 4
gpt4 key购买 nike

如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com