IndexError: tuple index out of range

Terry Reedy tjreedy at udel.edu
Sun May 31 00:35:52 CEST 2009


MRAB wrote:
> Invert wrote:
>> My simple python script gives me an error when I try to execute it.  
>> Here is the error message:
>>
>>     daniel at ibex:~/Desktop/python$ python3 str_format2Daniel.py
>>     Traceback (most recent call last):
>>       File "str_format2Daniel.py", line 8, in <module>
>>         print ("{0} is {1} years old {3} and ".format(name, age, append))
>>     IndexError: tuple index out of range
>>     daniel at ibex:~/Desktop/python$
>>
>>
>> Here is my script:
>>
>>     #!/usr/bin/python
>>     # Filename: str_format2.py
>>
>>     age = 23
>>     name = 'Daniel'
>>     append = '6 months'
>>
>>     print ("{0} is {1} years old {3} and ".format(name, age, append))
> 
> That should be:
> 
>     print ("{0} is {1} years old {2} and ".format(name, age, append))

Actually
print ("{0} is {1} years old and {2}".format(name, age, append))

> 
>>     print ('{0} will be an elite python programmer in {2}.'.format(name,
>>     append))

And the latter should replace 2 with 1.

>> What am I doing wrong?

Using position indexes that are too large.  In Py3.1, .format will 
auto-number fields, so the print statements could be

print("{} is {} years old and {}".format(name, age, append))
print ('{} will be an elite python programmer in {}.'.format(name, append))

Terry Jan Reedy





More information about the Python-list mailing list