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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "AttributeError: 'int' object has no attribute 'replace'" occurs when we call the replace() method on an integer. To solve the error, make sure the value you are calling replace on is of type string.

attributeerror int object has no attribute replace

Here is an example of how the error occurs.

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

We reassigned the my_str variable to an integer and tried to call the replace() method on the integer which caused the error.

If you print() the value you are calling replace() on, it will be an integer.

To solve the error, you need to track down where exactly you are setting the value to an integer in your code and correct the assignment.

To solve the error in the example, we would have to remove the reassignment or correct it.

main.py
my_str = 'zbc' result = my_str.replace('z', 'a') print(result) # 👉️ "abc"

If you are trying to replace digits in a number, convert the number to a string before calling replace().

main.py
my_num = 923 result = str(my_num).replace('9', '1') print(result) # 👉️ "123"

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

You might also be assigning the result of calling a function that returns an integer to a variable.

main.py
def get_string(): return 100 my_string = get_string() # ⛔️ AttributeError: 'int' object has no attribute 'replace' print(my_string.replace('z', 'a'))

The my_string variable gets assigned to the result of calling the get_string function.

The function returns an integer, so we aren't able to call replace() on it.

To solve the error, you have to track down where the specific variable gets assigned an integer instead of a string and correct the assignment.

Conclusion #

The Python "AttributeError: 'int' object has no attribute 'replace'" occurs when we call the replace() method on an integer. To solve the error, make sure the value you are calling replace on is of type string.

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.