Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
nerdfever.com Avatar asked Dec 25 '22 03:12

nerdfever.com


2 Answers

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.

like image 184
Hannes Ovrén Avatar answered Apr 29 '23 19:04

Hannes Ovrén


try

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

This builds a format string from the variable value.

like image 40
Lying Dog Avatar answered Apr 29 '23 19:04

Lying Dog