Search code examples
pythonpython-3.xstring-formatting

How to use variables for width and precision in str.format()?


How can I use a variable in the str.format() specification for width and precision?

(I'm in Python 3.)

This works fine:

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

But this gives an error:

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

Specifically, I get:

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

How can I use a variable for the precision and width?


Solution

  • Encase SHOWLEN in brackets

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

    This is evident from the following quote from the Format String Syntax documentation:

    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.