简体   繁体   English

这个奇怪的格式字符串“{[[[]}”有什么作用?

[英]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))

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 将打印1

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. 现在也许去看看文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM