str.format() with both alignment {:>} and variable interpolation

Viewed 1137

I am still trying to understand the new syntax for string formatting in Python.

"{fpath:>80}".format(fpath=path, flongest=longest)

The above code interpolates the path argument, and formats the string correctly, but replacing the text window value (80) with a variable gives ValueError: Invalid format specifier

"{fpath:>flongest}".format(fpath=path, flongest=longest)

How can the window size be assigned through a variable?

"{fpath:>???}".format(fpath=path, flongest=longest)
2 Answers

Okay, finally got it. The var 'longest' can be a string version of a number ('80') or an int (80). The trick is using curly brackets around only the right interpolated var.

"{fpath:>{flong}}".format(fpath=path, flong=longest)

Try to use this:

longest='{0}.format(variable value)'#let say 80
print('{fpath:>{flong}}'.format(fpath=path,flong=longest))

the variable length also needed to be converted into format specifier. I hope you understand. If still there is any problem then please let me know.

Related