AttributeError: str object has no attribute get error occurs because of invoking get() function/ attribute from str type object. Actually, this get() attribute is available in dict type object to values of a corresponding key.
Anyways, this error generally occurs in two main situations –
Since the Root cause is completly in two different directions. So we will resolve this error differently as well.
Let’s explore the error’s solution.
When we want to extract the value of str element at a specific index and we used get() function for this. Here we get this issue.
Here in the above code in sample_str when we use get() function to retrieve the element at the second index we get this error.
This is very common, In some cases, we took some input from config file or user. There we expect that the type of the input will be in key, value format which means dict type of object. But on the real ground or actual flow, The underline object remains str type which triggers this AttibuteError.
The best fix here is to apply to try and except the block and check the object type. Let’s understand with the below example.
obj="Input from usr"
try:
print(obj.get(2))
except:
print(" Invalid Input type")
print(type(obj))
To simply apply try and except can avoid multiple run time errors.
Thanks
Data Science Learner Team