-1

I am trying to format a dictionary and specify elements' width using the newer str.format():

>>> record = { 'name': 'Donald Trump', 'age': 12 }
>>> print "{name} {age}".format(**record)
Donald Trump 12
>>> # how would I set width for the name field to accommodate longer names

How do I use a combination of dictionary attributes access and formatting like width control?

sagism
  • 881
  • 4
  • 11
  • 18
  • 2
    You are asking for 3 elements. One is "silent" before the `:`. Simply change to: `print "{name:>30} {age}".format(**record)` – Tomerikoo Jun 30 '19 at 10:09
  • Thats the answer but sagism can't accept a comment :) – Raphael Jun 30 '19 at 10:11
  • 1
    Read this [pyformat summary](https://pyformat.info/) which has a lot of different formatting options and helpful explanations – Tomerikoo Jun 30 '19 at 10:30

1 Answers1

1

Here's the correct syntax:

In [31]: print("{name} {age}".format(**record))                                                                                                                                                                                                               
Donald Trump 12

In [32]: print("{name:>30} {age}".format(**record))                                                                                                                                                                                                           
                  Donald Trump 12

In [33]: print("{name:30} {age}".format(**record))                                                                                                                                                                                                            
Donald Trump                   12

Notice that I am using Python 3.7, you should remove the parenthesis from the print method if you're using Python<3 (which I do not recommend).

From Python docs:

align ::= "<" | ">" | "=" | "^"

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered
AdamGold
  • 4,941
  • 4
  • 29
  • 47