Replacement index 1 out of range for positional args tuple

avatar

Borislav Hadzhiev

Last updated: Apr 22, 2022

banner

Photo from Unsplash

Replacement index 1 out of range for positional args tuple #

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.

indexerror replacement index 1 out of range

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
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.

main.py
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.

main.py
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.

main.py
first = 'James' last = 'Doe' result = "His name is {f} {l}".format(f=first, l=last) print(result) # 👉️ "His name is James Doe"
Make sure to provide exactly as many arguments to the 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.

main.py
first = 'James' last = 'Doe' result = f'His name is {first} {last}' print(result) # 👉️ "His name is James Doe"
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.