How To Solve “AttributeError: ‘Str’ Object Has No Attribute ‘Trim'” In Python

How To Solve AttributeError: ‘Str’ Object Has No Attribute ‘Trim’ In Python

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'.

The reason behind the lack of the method trim() is that you have forgotten that there is no method like that in Python. In fact, the trim() method is used to remove any whitespace from both sides of a string and then return a new string with no blank spaces at the beginning and the end of the string. This method is well-known in JavaScript and many programming languages:

let string = ' LEARNSHAREIT  '
console.log(string.trim())

Output

LEARNSHAREIT

How to solve this error?

Using strip()

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)

Output

LEARNSHAREIT

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+"|")

Output

| 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.

Summary

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:

Leave a Reply

Your email address will not be published. Required fields are marked *