In Python, the str() function is used for converting a certain value into a string. It takes an object as an argument and converts it into a string. As str is the name of a pre-defined function in Python and is a reserved keyword, it cannot be used anywhere else. So if you use str for naming a variable or a function, the Python compiler will throw an error. As a result, you will encounter a “TypeError 'str' object is not callable in Python” error.
In this article, we will look at a process to resolve this error.
Cause of TypeError: 'str' object is not callable in Python
This is a common error that occurs when the user declares a variable with the same name as inbuilt function str() used in the code.
Python compiler treats str as a variable name, but in our program, we are also using in-built function str() as a function. Due to this python compiler get confused and generate an error: typeerror: 'str' object is not callable
str = "Hi This is" str1 = " Stechies" print(str(str + str1))
Traceback (most recent call last): File "str.py", line 4, in <module> print(str(str + str1)) TypeError: 'str' object is not callable
In the above example, we are joining two string variables with (+) operator, but we declared a variable named as “str” and on the next line we are using str() function.
So python compiler takes “str” as a variable, not as function due to which error “TypeError: 'str' object is not callable” occurs.
How to Resolve typeerror: 'str' object is not callable
To resolve this error, you need to change the name of the variable whose name is similar to the in-built function str() used in the code.
str2 = "Hi This is" str1 = " STechies" print(str(str2 + str1))
Hi This is STechies
In the above example, we have just changed the name of variable “str” to “str2”.
Conclusion: Don’t use any variable which has the same name as any in-built python function used in your code.