Last updated: Apr 8, 2024
Reading timeยท2 min
The Python "IndexError: Replacement index 1 out of range for positional args
tuple" occurs when we use the format()
method without providing a value for
all replacement fields.
To solve the error, make sure to provide a value for each replacement field.
Here is an example of how the error occurs.
# โ๏ธ IndexError: Replacement index 1 out of range for positional args tuple my_str = 'His name is {} {}'.format('Bobby')
Notice that we only passed a value for the first replacement field.
To solve the error, make sure to specify a value for each replacement field.
my_str = 'His name is {} {}'.format('Bobby', 'Hadz') print(my_str) # ๐๏ธ 'His name is Bobby Hadz'
The string in the example has 2 replacement fields {}
, so we passed 2
arguments to the str.format()
method.
If you only meant to have 1 replacement field, remove the second one.
my_str = 'His name is {}'.format('Bobby') print(my_str) # ๐๏ธ His name is Bobby
The string in the example has only 1 replacement field, so we passed a single
argument in the call to format()
.
If you have an iterable (e.g. a list or a tuple), use an asterisk to unpack the iterable's items.
my_list = ['Bobby', 'Hadz'] my_str = 'His name is {} {}'.format(*my_list) print(my_str) # ๐๏ธ 'His name is Bobby Hadz'
The asterisk *
unpacks the items of the iterable in the call to the format()
method.
When using unpacking, you have to make sure the iterable has exactly as many
elements as there are replacement fields {}
in the string.
The str.format() method performs string formatting operations.
first = 'Bobby' last = 'Hadz' result = "His name is {0} {1}".format(first, last) print(result) # ๐๏ธ "His name is Bobby Hadz"
The string the method is called on can contain replacement fields specified
using curly braces {}
.
You can also use keyword arguments instead of positional ones.
first = 'Bobby' last = 'Hadz' result = "His name is {f} {l}".format(f=first, l=last) print(result) # ๐๏ธ "His name is Bobby Hadz"
format()
method as you have replacement fields in the string.If you decide to use positional arguments with numeric indices, make sure to
start from 0
, e.g. {0}
as indices are zero-based in Python.
Alternatively, you can use a formatted string literal to concatenate strings.
first = 'Bobby' last = 'Hadz' result = f'His name is {first} {last}' print(result) # ๐๏ธ "His name is Bobby Hadz"
f
.Make sure to wrap expressions in curly braces - {expression}
.
This should be your preferred approach as formatted string literals are a more recent addition to Python and offer a much easier-to-read syntax.