Fix the 'str' object is not callable error in Python
In this tutorial, we are going to learn how to fix the TypeError: ‘str’ object is not callable in Python.
This error occurs for one of the following reasons:
-
If you try to use an
str()
built-in function as a variable name. -
Using the parenthesis
()
instead of square brackets[]
to access the characters from a string at a specific index.
Example:
str = 'Hello' # using str as a variable name
print(str(2)) # using parenthesis to access characters
Output:
TypeError:'str' object is not callable
To fix the error, use the square brackets []
syntax to access the characters from a list, and do not use the str
keyword as a variable name because it is reserved for the str()
function in python.
Here is an example:
greet = 'Hello'
print(greet[0]) # H'
print(greet[2]) # 'e'
Another cause of the error is calling the string value like a function :
greet_str = 'Hello'
# TypeError: 'str' object is not callable
print(greet_str())
Conclusion
The “str” object is not a callable error that occurs when we try to use the str
as a variable name and using the parenthesis ()
to access the characters from a string. To fix the error always use the square brackets []
to access the characters at a specific index eg: user_str[1]
and do not use the str()
built-in keyword as a variable name because it is reserved for str()
function in python.