“AttributeError: ‘str’ object has no attribute ‘trim’ in Python” is a common error related to Python string objects. The below explanations can help you know more about the causes of this error and solutions.
How does the AttributeError: ‘str’ object has no attribute ‘trim’ in Python happen?
Basically, “no attribute ‘trim’” means that the object or the instance you call the method on does not have any defined method named trim(). Mostly, the error will happen when you call this method on a string in Python. For example:
string = ' LEARNSHAREIT ' print (string.trim())
Traceback (most recent call last): File "main.py", line 2, in <module> print (string.trim()) AttributeError: 'str' object has no attribute 'trim'.
let string = ' LEARNSHAREIT ' console.log(string.trim())
How to solve this error?
Fortunately, Python has another method that works exactly like the trim() method you expect. To use this method, call it on your string variable:
string = ' LEARNSHAREIT ' trim = string.strip() print (trim)
The strip() method produces a new string which is the original string with whitespaces from both left and right sides removed. However, if you may want to remove whitespace in the front only, or in the end of the string only, then the following solutions should be taken into consideration.
Using lstrip() and rstrip()
Another way to overcome this problem is to remove the leading whitespaces from a string first and then remove the trailing ones:
string = ' LEARNSHAREIT ' print ("|"+string+"|") trim1 = string.lstrip() print ("|"+trim1+"|") trim2 = trim1.rstrip() print ("|"+trim2+"|")
| LEARNSHAREIT | |LEARNSHAREIT | |LEARNSHAREIT|
The above example used the lstrip() method on our original string to return a string with leading spaces removed. Then we called the rstrip() method on the string with no leading whitespaces (trim1) to get the new string without trailing whitespaces.
We have learned how to solve AttributeError: ‘str’ object has no attribute ‘trim’ in Python. You can easily avoid this error by finding out the reasons in our tutorial and replacing a function that doesn’t exist.
Maybe you are interested:
- How To Resolve AttributeError: ‘str’ Object Has No Attribute ‘append’ In Python
- How To Solve IndexError: String Index Out Of Range In Python
- How To Solve The Error “ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] Wrong Version Number (_ssl.c:1056)” In Python
Name of the university: HCMUT