AttributeError: 'tuple' object has no attribute 'replace'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Robert Bye

AttributeError: 'tuple' object has no attribute 'replace' #

The Python "AttributeError 'tuple' object has no attribute 'replace'" occurs when we call the replace() method on a tuple instead of a string. To solve the error, correct the assignment of the variable or access the tuple at a specific index when calling replace().

attributeerror tuple object has no attribute replace

Here is an example of how the error occurs.

main.py
example = 'zbc', 'def' print(type(example)) # 👉️ <class 'tuple'> # ⛔️ AttributeError: 'tuple' object has no attribute 'replace' result = example.replace('z', 'a')

We declared a tuple instead of a string by separating multiple values with a comma.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

To be able to use the replace() method, we have to declare a string, or access the tuple at a specific index.

main.py
example = 'zbc def' print(type(example)) # 👉️ <class 'string'> result = example.replace('z', 'a') print(result) # 👉️ "abc def"

We declared a string, so we were able to use the replace() method to replace the z character with an a.

If you meant to call replace() on an element of a tuple, access it at the specific index.

main.py
my_tuple = ('zbc', 'def') result = my_tuple[0].replace('z', 'a') print(result) # 👉️ "abc"

We accessed the tuple element at index 0 which is a string, so we were able to call the replace() method.

Tuples are constructed in multiple ways:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

Note that tuples are immutable, so if you have to mutate a sequence, you have to use a list instead.

There are only 2 methods that you will likely be using on tuple objects.

main.py
my_tuple = ('a', 'b', 'c', 'c') print(my_tuple.count('c')) # 👉️ 2 print(my_tuple.index('a')) # 👉️ 0

The count method returns the number of occurrences of the value in the tuple and the index method returns the index of the value in the tuple.

You can view all the attributes an object has by using the dir() function.

main.py
my_tuple = ('a', 'b', 'c', 'c') # 👇️ [... 'count', 'index' ...] print(dir(my_tuple))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: tuple object has no attribute" error.

Use the search field on my Home Page to filter through my more than 1,000 articles.