How To Solve TypeError: ‘str’ object is not callable in Python

Every language has a series of keywords. When naming a variable with the same keyword, an error will appear. For example, when you use the str keyword to name a variable, this will result in the error TypeError: ‘str’ object is not callable. The Error can also occur when forgetting to use % character while formatting the string. Let’s find out together.

Causes of TypeError: ‘str’ object is not callable.

The Error occurs when we set str as the variable’s name, the word coincides with the string object keyword in Python, or when you make a function call on a string object. Take a look at the examples below.

In this example, instead of using a noun to name the variable, we use the word str to name the variable, and so the Error occurs.

Error Example:

# Use the word str to name the variable
str = "Peter"
name = "Mary"
print(str(str + name))

Output:

TypeError: 'str' object is not callable

The second reason that can cause this Error is that you format the string with the % character. We forgot to add the % character to separate the string and variable parts.

Error Example:

name1 = "Peter"
name2 = "Mary"

# Forgot to add the % character to separate the string and variable parts
print("%s %s"(name1, name2))

Output:

TypeError: 'str' object is not callable

Workarounds for TypeError: ‘str’ object is not callable

We need to avoid naming the variable as str to solve this Error. It would help if you used a noun to name the variable, making it easier for you and others to understand the code. You should also avoid calling the string object like calling a function because the string object does not provide this method. And remember to use the % sign while formatting the string.

Avoid using str to name variables.

It would help if you used nouns to name variables and avoid using the keyword str.

Example:

# Change "str" to "name1"
name1 = "Peter"
name2 = "Mary"
print(str(name1 + " " + name2))

Output:

Peter Mary

Don’t forget the % character when formatting strings.

When using the % character to format a string, note that you need to add a % character to separate the string and variable parts.

Example:

name1 = "Peter"
name2 = "Mary"

# Add a % character to separate the string and variable parts
print("%s %s" %(name1, name2))

Output:

Peter Mary

Summary

Through this article, you have understood the reason for the TypeError: the ‘str’ object is not callable in Python and some ways to fix it. This Error occurs when you call a string object as calling a function. To avoid this error, you should not name the variable as “str“. So together, we fixed the Error. Thanks for reading

Leave a Reply

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