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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

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

attributeerror int object has no attribute isdigit

Here is an example of how the error occurs.

main.py
my_str = '123' my_str = 123 # ⛔️ AttributeError: 'int' object has no attribute 'isdigit' print(my_str.isdigit())

We reassigned the my_str variable to an integer and tried to call the isdigit() method on the integer which caused the error because isdigit is a string method.

If you print() the value you are calling isdigit() 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 = '123' print(my_str.isdigit()) # 👉️ True

If the variable is intended to store an integer, you can remove the call to the isdigit method as integers are digits.

If you want to silence the error and can't remove the method call, convert the integer to a string before calling isdigit().

main.py
my_num = '123' print(str(my_num).isdigit()) # 👉️ True

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

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 'isdigit' print(my_string.isdigit())

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 isdigit() 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.

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.