Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Mark Galer
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.
Here is an example of how the error occurs.
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.
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.
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()
.
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.
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.