请考虑以下代码段:
>>> def foo(port, out, udp=False, ipv6=False, data=''):
... if not data:
... data = 'foo {family} {:port} {direction}'.format(
... family=('ipv6' if ipv6 else 'ipv4'),
... port=port,
... direction=('out' if out else 'in'))
... return data
...
>>> foo(12345, out=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in foo
IndexError: tuple index out of range
据我所知,名字的范围看起来不错。什么是神秘的错误?
答案 0 :(得分:2)
观察结肠。将其从端口区域的前面移开:
无论
data = 'foo {family} {port:} {direction}'.format(
或者
data = 'foo {family} :{port} {direction}'.format(
两个选项的结果是:
>>> foo(12345, out=True)
'foo ipv4 12345 out'
>>> foo(12345, out=True)
'foo ipv4 :12345 out'
答案 1 :(得分:0)
{:port}
应为{port:}
。