Python ''.format():出现“元组索引超出范围”?

3 投票
2 回答
12325 浏览
提问于 2025-04-16 04:12

考虑以下这段代码:

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

据我所知,变量的作用域看起来没问题。那这个难懂的错误是怎么回事呢?

2 个回答

0

{:port} 应该改成 {port:}

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'    

撰写回答