2016-08-18 110 views
4

我在前員工的一些代碼中發現了以下內容。這個奇怪的格式字符串「{[[[]}」是做什麼的?

從任何地方都不會調用代碼,但是我的問題是它可以真正做一些有用的事情嗎?

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

標題和代碼中使用的字符串是不同的。標題有三個左括號,代碼有四個... –

回答

4

這是一個格式字符串用空的參數名稱和元素索引([]之間的部分爲重點[[[(這些索引不必是整數),這將打印值該密鑰

呼叫:

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

將打印1

0

在e可以使用交互式解釋器來調查這樣的實驗。

>>> 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 

現在也許去閱讀文檔。

相關問題