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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Mark Galer

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

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

attributeerror int object has no attribute strip

Here is an example of how the error occurs.

main.py
my_string = ' hello ' my_string = 100 print(type(my_string)) # 👉️ <class 'int'> print(my_string.strip())

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

If you print() the value you are calling strip() 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.

If the value is expected to be an integer, there is no point of calling strip() on it and you can remove the call to the method.

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

main.py
my_string = ' hello ' print(my_string.strip()) # "hello"

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

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

main.py
example = 100 print(str(example).strip()) # 👉️ "100"

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

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

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