AttributeError: ‘str’ 对象没有属性 ‘trim’

AttributeError: ‘str’ 对象没有属性 ‘trim’

AttributeError: ‘str’ object has no attribute ‘trim’

Python“AttributeError: ‘str’ object has no attribute ‘trim’” 发生在我们尝试对trim()字符串调用该方法时。要解决该错误,请使用该
strip()方法从字符串中删除前导和尾随空格。

attributeerror str 对象没有属性修剪

下面是错误如何发生的示例。

主程序
my_str = ' hello world ' # ⛔️ AttributeError: 'str' object has no attribute 'trim'. Did you mean: 'strip'? result = my_str.trim()

trim()字符串在 Python 中
没有方法,但是您可以使用该
strip()方法从字符串中删除任何前导或尾随空格。

主程序
my_str = ' hello world ' result = my_str.strip() print(result) # 👉️ "hello world"

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

该方法不改变原来的字符串,它返回一个新的字符串。字符串在 Python 中是不可变的。

确保将新字符串存储在变量中,因为原始字符串保持不变。

您可以使用该lstrip方法从字符串中删除任何前导空格。

主程序
my_str = ' hello world ' result1 = my_str.lstrip() print(result1) # 👉️ "hello world "

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

相反,您可以使用该rstrip方法删除任何尾随空格。

主程序
my_str = ' hello world ' result2 = my_str.rstrip() print(result2) # 👉️ " hello world"

str.rstrip方法返回删除
尾随空格的字符串副本。

开始调试的一个好方法是print(dir(your_object))查看字符串具有哪些属性。

这是打印 a 的属性的示例string

主程序
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

如果将一个类传递给
dir()函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。

如果您尝试访问不在此列表中的任何属性,您将收到“AttributeError:str object has no attribute error”。

由于该str对象未实现trim()方法,因此导致错误。

结论

Python“AttributeError: ‘str’ object has no attribute ‘trim’” 发生在我们尝试对trim()字符串调用该方法时。要解决该错误,请使用该
strip()方法从字符串中删除前导和尾随空格。