Borislav Hadzhiev
Last updated: Apr 22, 2022
Photo from Unsplash
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 = 'Her name is {} {}'.format('Alice')
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 = 'Her name is {} {}'.format('Alice', 'Smith') print(my_str) # 👉️ 'Her name is Alice Smith'
If you have an iterable (e.g. a list or a tuple), use an asterisk to unpack the iterable's items.
my_list = ['Alice', 'Smith'] my_str = 'Her name is {} {}'.format(*my_list) print(my_str) # 👉️ 'Her name is Alice Smith'
The asterisk unpacks the items of the iterable in the call to the format()
method.
The str.format method performs string formatting operations.
first = 'James' last = 'Doe' result = "His name is {0} {1}".format(first, last) print(result) # 👉️ "His name is James Doe"
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 = 'James' last = 'Doe' result = "His name is {f} {l}".format(f=first, l=last) print(result) # 👉️ "His name is James Doe"
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 = 'James' last = 'Doe' result = f'His name is {first} {last}' print(result) # 👉️ "His name is James Doe"
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.