Python 中 AttributeError: ‘int’ object has no attribute ‘strip’ 错误

当我们对整数调用 strip() 方法时,会出现 Python“AttributeError: ‘int’ object has no attribute ‘strip’ ”。 要解决该错误,请确保调用 strip 的值是字符串类型。

下面是一个产生上述错误的示例代码

my_string = '   hello   '

my_string = 100

print(type(my_string))  # 👉️ <class 'int'>

print(my_string.strip())

Python 中 AttributeError: 'int' object has no attribute 'strip' 错误

我们将 my_string 变量重新分配给一个整数,并尝试对导致错误的整数调用 strip() 方法。

如果我们使用 print() 打印我们调用 strip() 的值,它将是一个整数。

要解决该错误,我们需要查明在代码中将值设置为整数的确切位置并更正分配。

如果该值预期为整数,则没有必要对其调用 strip() 并且您可以删除对该方法的调用。

要解决示例中的错误,我们必须删除重新分配或更正它。

my_string = '   hello   '

print(my_string.strip())  # "hello"

str.strip 方法返回删除了前导和尾随空格的字符串副本。

如果我们需要消除错误并且不能删除对 strip() 的调用,我们可以在调用 strip() 之前将整数转换为字符串。

example = 100

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

我们还可以将调用返回整数的函数的结果分配给变量。

def get_string():
    return 100


my_string = get_string()

# ⛔️ AttributeError: 'int' object has no attribute 'strip'
print(my_string.strip())

my_string 变量被分配给调用 get_string 函数的结果。

该函数返回一个整数,因此我们无法对其调用 strip()

要解决该错误,我们必须找到为特定变量分配整数而不是字符串的位置并更正分配。