blackknight
blackknight

Reputation: 67

What does this strange format string "{[[[]}" do?

I come across the below in some code from an ex employee.

the code is not called, from anywhere, but my question is can it actually do something useful as it is?

def xshow(x):
    print("{[[[[]}".format(x))

Upvotes: 4

Views: 248

Answers (2)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

One can use the interactive interpreter to investigate something like this experimentally.

>>> xshow(None)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    xshow(None)
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
TypeError: 'NoneType' object is not subscriptable

# So let us try something subscriptable.
>>> xshow([])
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    xshow([])
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
TypeError: list indices must be integers or slices, not str

# That did not work, try something else.
>>> xshow({})
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    xshow({})
  File "<pyshell#11>", line 1, in xshow
    def xshow(x): print("{[[[[]}".format(x))
KeyError: '[[['

# Aha! Try a dict with key '[[['.
>>> xshow({'[[[':1})
1

Now maybe go read the doc.

Upvotes: 0

Anthon
Anthon

Reputation: 76608

That is a format string with an empty argument name and an element index (the part between [ and ] for a key [[[ (those indices don't have to be integers). It will print the value for that key.

Calling:

xshow({'[[[': 1})

will print 1

Upvotes: 4

Related Questions