0

Can anyone help me to change the writing of these lines? I want to get my code to be more elegant using .format(), but I don't really know how to use it.

print("%3s %-20s %12s" %("Id", "State", "Population"))
print("%3d %-20s %12d" %
            (state["id"],
             state["name"],
             state["population"]))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ArrowsX
  • 505
  • 1
  • 4
  • 9

2 Answers2

1

Your format is easily translated to the str.format() formatting syntax:

print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
print("{id:3d} {name:20s} {population:12d}".format(**state))

Note that left-alignment is achieved by prefixing the width with <, not -, and default alignment for strings is to left-align, so a > is needed for the header strings and the < can be omitted, but otherwise the formats are closely related.

This extracts the values directly from the state dictionary by using the keys in the format itself.

You may as well just use the actual output result of the first format directly:

print(" Id State                  Population")

Demo:

>>> state = {'id': 15, 'name': 'New York', 'population': 19750000}
>>> print("{:>3s} {:20s} {:>12s}".format("Id", "State", "Population"))
 Id State                  Population
>>> print("{id:3d} {name:20s} {population:12d}".format(**state))
 15 New York                 19750000
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can write:

print("{id:>3s} {state:20s} {population:>12s}".format(id='Id', state='State', population='Population'))
print("{id:>3d} {state:20s} {population:>12d}".format(id=state['id'], state=state['name'], population=state['population']))

Note that you have to use > to right-align as the items are left-aligned by default. You can also name the items in the formatted string which makes it more readable to see what value goes where.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180