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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

attributeerror int object has no attribute split

Here is an example of how the error occurs.

main.py
my_string = 'hello,world' my_string = 100 print(type(my_string)) # <class 'int'> # ⛔️ AttributeError: 'int' object has no attribute 'split' print(my_string.split(','))

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

If you print() the value you are calling split() 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_string = 'hello,world' print(my_string.split(',')) # 👉️ ['hello', 'world']

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If you need to silence the error and can't remove the call to split() you can convert the integer to a string before calling split().

main.py
example = 123 print(str(example).split(',')) # 👉️ ['123']

If the separator is not found in the string, a list containing only 1 element 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 'split' print(my_string.split(','))

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 split() 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 'split'" occurs when we call the split() method on an integer. To solve the error, make sure the value you are calling split 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.