开发者

Converting dynamic, nicely formatted tabular data in Python to str.format()

I have the following Python 2.x code, which generates a header row for tabular data:

headers = ['Name', 'Date', 'Age']
maxColumnWidth = 20 # this is just a placeholder
headerRow = "|".join( ["%s" % k.center(maxColumnWidth) for k in headers] )
print(headerRow)

This code outputs the following:

         Name          |        Date        |          Age         

Which is exactly what I want - the data is nicely formatted and centered in columns of width maxColumnWidth. (maxColumnWidth is calculated earlier in the program)

According to the Python docs, you should be able to do the same thing 开发者_如何转开发in Python3 with curly brace string formatting, as follows:

headerRow = "|".join( ["{:^maxColumnWidth}".format(k) for k in headers] )

However, when I do this, I get the following:

ValueError: Invalid conversion specification

But, if I do this:

headerRow = "|".join( ["{:^30}".format(k) for k in headers] )

Everything works fine. My question is: How do I use a variable in the format string instead of an integer?:

headerRow = "|".join( ["{:^maxColumnWidth}".format(k) for k in headers] )


headers = ['Name', 'Date', 'Age']
maxColumnWidth=21
headerRow = "|".join( "{k:^{m}}".format(k=k,m=maxColumnWidth) for k in headers )
print(headerRow)

yields

        Name        |        Date        |        Age         
  1. You can represent the width maxColumnWidth as {m}, and then substitute the value through a format parameter.
  2. No need to use brackets (list comprehension) inside the join. A generator expression (without brackets) suffices.


As it says, your conversion specification is invalid. "maxColumnWidth" is not a valid conversion specification.

>>> "{:^{maxColumnWidth}}".format('foo', maxColumnWidth=10)
'   foo    '
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜