-1

again :)

I found this bit of code

col_width=[13,11]
header=['First Name','Last Name']

format_specs = ["{{:{}}}".format(col_width[i]) for i in range(len(col_width))]
lheader=[format_specs[i].format(self.__header[i]) for i in range(nb_columns)]

How Python evaluate this statement? Why we use three { when we have one element to format in every iteration?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Ado Riadh
  • 19
  • 7
  • 2
    Why are you tagging this with a Python 2 and a Python 3 tag? Which is it? does it even matter? Please don't use inappropriate tags. – juanpa.arrivillaga Oct 25 '16 at 22:38
  • Read the [docs](https://docs.python.org/3/library/string.html#formatstrings). – user2357112 Oct 25 '16 at 22:41
  • 1
    Note: You could avoid the two pass solution here; Python can already format with a user provided width. The first outer bracket corresponds to the first positional argument, so your two pass code could be written as a single pass with: `lheader = ['{:{}}'.format(h, w) for h, w in zip(header, col_width)]` or even `lheader = list(map('{:{}}'.format, header, col_width))`. Since automatic numbering isn't 100% obvious here, you could use `'{0:{1}}'` as your format string, just to make it clear that the value is the first argument and the width is the second. – ShadowRanger Oct 26 '16 at 00:48

1 Answers1

1

when you do {{}}, python skips the replacement of {} and makes it the part of string. Below is the sample example to explain this:

>>> '{{}}'.format(3)  # with two '{{}}'
'{}'  # nothing added to the string, instead made inner `{}` as the part of string
>>> '{{{}}}'.format(3)  # with three '{{{}}}'
'{3}'  # replaced third one with the number

Similarly, your expression is evaluating as:

>>> '{{:{}}}'.format(3)
'{:3}'  # during creation of "format_specs"

For details, refer: Format String Syntax document.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126