Str object is not callable python ошибка

The first error is in the line

ans = raw_input().lower()("This is one of those times when only Yes/No will do!"
                          "n"  "So what will it be? Yes? No?")

The result of lower() is a string, and parentheses after that mean that the object on the left (the string) gets called. Therefore, you get your error. You want

ans = raw_input("This is one of those times when only Yes/No will do!n"
                "So what will it be? Yes? No?").lower()

Also,

if ans() == 'yes' or 'no':

does not what you expect. Again, ans is a string, and parentheses mean that the object on the left (the string) gets called. Therefore, you get your error.

Also, or is a logical operator. Even after removing the parentheses after ans, the code gets evaluated as:

if (ans == 'yes') or ('no'):

Since a non-empty string ('no') evaluates to the boolean value True, this expression is always True. You simply want

if ans in ('yes', 'no'):

Additionally, you want to unindent the last lines. All in all, try:

name = raw_input("Welcome soldier. What is your name? ")
print('Ok, ' + name + ' we need your help.')
ans = raw_input("Do you want to help us? (Yes/No)").lower()
while True:
    if ans in ('yes', 'no'):
        break
    print("This is one of those times when only Yes/No will do!n")
    ans = raw_input("So what will it be? Yes? No?").lower()

if ans == "yes":
    print("Good!")
elif ans == "no":
    print("I guess I was wrong about you..." 'n' "Game over.")

Typeerror: str object is not callable – How to Fix in Python

Every programming language has certain keywords with specific, prebuilt functionalities and meanings.

Naming your variables or functions after these keywords is most likely going to raise an error. We’ll discuss one of these cases in this article — the TypeError: 'str' object is not callable error in Python.

The TypeError: 'str' object is not callable error mainly occurs when:

  • You pass a variable named str as a parameter to the str() function.
  • When you call a string like a function.

In the sections that follow, you’ll see code examples that raise the TypeError: 'str' object is not callable error, and how to fix them.

Example #1 – What Will Happen If You Use str as a Variable Name in Python?

In this section, you’ll see what happens when you used a variable named str as the str() function’s parameter.

The str() function is used to convert certain values into a string. str(10) converts the integer 10 to a string.

Here’s the first code example:

str = "Hello World"

print(str(str))
# TypeError: 'str' object is not callable

In the code above, we created a variable str with a value of «Hello World». We passed the variable as a parameter to the str() function.

The result was the TypeError: 'str' object is not callable error. This is happening because we are using a variable name that the compiler already recognizes as something different.

To fix this, you can rename the variable to a something that isn’t a predefined keyword in Python.

Here’s a quick fix to the problem:

greetings = "Hello World"

print(str(greetings))
# Hello World

Now the code works perfectly.

Example #2 – What Will Happen If You Call a String Like a Function in Python?

Calling a string as though it is a function in Python will raise the TypeError: 'str' object is not callable error.

Here’s an example:

greetings = "Hello World"

print(greetings())
# TypeError: 'str' object is not callable

In the example above, we created a variable called greetings.

While printing it to the console, we used parentheses after the variable name – a syntax used when invoking a function: greetings().

This resulted in the compiler throwing the TypeError: 'str' object is not callable error.

You can easily fix this by removing the parentheses.

This is the same for every other data type that isn’t a function. Attaching parentheses to them will raise the same error.

So our code should work like this:

greetings = "Hello World"

print(greetings)
# Hello World

Summary

In this article, we talked about the TypeError: 'str' object is not callable error in Python.

We talked about why this error might occur and how to fix it.

To avoid getting this error in your code, you should:

  • Avoid naming your variables after keywords built into Python.
  • Never call your variables like functions by adding parentheses to them.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Table of Contents
Hide
  1. What is typeerror: ‘str’ object is not callable in Python?
  2. Scenario 1 – Declaring a variable name called “str”
  3. Solving typeerror: ‘str’ object is not callable in Python.
  4. Scenario 2 – String Formatting Using %

One of the most common errors in Python programming is typeerror: ‘str’ object is not callable, and sometimes it will be painful to debug or find why this issue appeared in the first place.

Python has a built-in method str() which converts a specified value into a string. The str() method takes an object as an argument and converts it into a string.

Since str() is a predefined function and a built-in reserved keyword in Python, you cannot use it in declaring it as a variable name or a function name. If you do so, Python will throw a typeerror: ‘str‘ object is not callable.

Let us take a look at few scenarios where you could reproduce this error.

Scenario 1 – Declaring a variable name called “str”

The most common scenario and a mistake made by developers are declaring a variable named ‘str‘ and accessing it. Let’s look at a few examples of how to reproduce the ‘str’ object is not callable error.

str = "Hello, "
text = " Welcome to ItsMyCode"

print(str(str + text))

# Output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 4, in <module>
    print(str(str + text))
TypeError: 'str' object is not callable

In this example, we have declared ‘str‘ as a variable, and we are also using the predefined str() method to concatenate the string.

str = "The cost of apple is "
x = 200
price= str(x)
print((str + price))

# output
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 3, in <module>
    price= str(x)
TypeError: 'str' object is not callable

The above code is similar to example 1, where we try to convert integer x into a string. Since str is declared as a variable and if you str() method to convert into a string, you will get object not callable error.

Solving typeerror: ‘str’ object is not callable in Python.

Now the solution for both the above examples is straightforward; instead of declaring a variable name like “str” and using it as a function, declare a more meaningful name as shown below and make sure that you don’t have “str” as a variable name in your code.

text1 = "Hello, "
text2 = " Welcome to ItsMyCode"

print(str(text1 + text2))

# Output
Hello,  Welcome to ItsMyCode
text = "The cost of apple is "
x = 200
price= str(x)
print((text + price))

# Output
The cost of apple is 200

Scenario 2 – String Formatting Using %

Another hard-to-spot error that you can come across is missing the % character in an attempt to append values during string formatting.

If you look at the below code, we have forgotten the string formatting % to separate our string and the values we want to concatenate into our final string. 

print("Hello %s its %s day"("World","a beautiful"))

# Output 
Traceback (most recent call last):
  File "c:ProjectsTryoutslistindexerror.py", line 1, in <module>
    print("Hello %s its %s day"("World","a beautiful"))
TypeError: 'str' object is not callable

print("Hello %s its %s day"%("World","a beautiful"))

# Output
Hello World its a beautiful day

In order to resolve the issue, add the % operator before replacing the values ("World","a beautiful") as shown above.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

So you have encountered the exception, i.e., TypeError: ‘str’ object is not callable. In the following article, we will discuss type errors, how they occur and how to resolve them.

What is a TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage. The Python interpreter immediately raises a type error when it encounters an error, usually along with an explanation. For instance:

val1 = 100
val2 = "random text"

print(val1/val2)

When you try to divide an integer value with a string, it results in a type error.

TypeError Example

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

So you have encountered the exception, i.e., TypeError: ‘str’ object is not callable. In the following article, we will discuss type errors, how they occur and how to resolve them.

What is a TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage. The Python interpreter immediately raises a type error when it encounters an error, usually along with an explanation. For instance:

val1 = 100
val2 = "random text"

print(val1/val2)

When you try to divide an integer value with a string, it results in a type error.

TypeError Example

TypeError Example

Like any TypeError, the ‘str’ object is not callable occurs when we try to perform an operation not supported by that datatype. In our case, here it’s the ‘string’ datatype. Let’s see some examples of where it can occur and how we can resolve them.

Example 1:

str = "This is text number 1"
string2 = "This is text number 2"

print(str(str) + string2)

In the code above, we have deliberately defined the first variable name with a reserved keyword called str. Moreover, the second variable, string2, follows Python’s naming conventions. In the print statement, we use the str method on the str variable, this confuses the Python’s interpreter, and it raises a type error, as shown in the image below.

The output of example 1

The output of example 1

Example 2:

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" (string1,string2))

Contrary to example 1, where we had defined a variable with the str reserved keyword, which raised an error. In the example 2 code, we are using the ‘ % ‘ operator to perform string formatting. However, there is a minor issue in the syntax. We have omitted the % before the tuple. Missing this symbol can raise a similar error.

The output of example 2

The output of example 2

How to resolve this error?

The solution to example 1:

In Python, the str() function converts values into a string. It takes an object as an argument and converts it into a string. The str is a pre-defined function and also a reserved keyword. Therefore, it can’t be used as a variable name as per Python’s naming conventions.

To resolve the error, use another variable name.

string1 = "This is text number 1"
string2 = "This is text number 2"

print(str(string1) + string2)

Using proper naming convention, error gets resolved.

Using proper naming convention, the error gets resolved.

The solution to example 2:

In example 2, we tried to use string formatting to display string1 and string2 together. However, not using the % operator before the tuples of values TypeError: ‘str’ object is not a callable error that gets thrown. To resolve it, use the % operator in its proper place.

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" %(string1,string2))

Using the % operator at its right place resolves the error

Using the % operator in its right place resolves the error

TypeError: ‘str’ object is not callable Selenium

This error is likely due to accidentally invoking a function() which is actually a property. Please check your code for this.

TypeError ‘str’ object is not callable BeautifulSoup/Django/Collab

Irrespective of the library used, this error can creep in if you have used some reserved keyword as a variable or redefined some property or a function of the library. Please check your code for such things.

TypeError ‘str’ object is not callable matplotlib

Somewhere in the code, you might have used plt.xlabel = “Some Label”. This will change the import of matplotlib.pyplot. Try to close the Notebook and restart your Kernel. After the restart, rerun your code, and everything should be fine.

FAQs

How do I fix the str object that is not callable?

To fix this error, you need to ensure that no variable is named after the str reserved keyword. Change it if this is the case.

What does str object is not callable mean?

TypeError generally occurs if an improper naming convention has been used, in other words, if the str keyword is used as a variable name.

TypeError ‘str’ object is not callable pyspark

This error is likely due to accidentally overwriting one of the PySpark functions with a string. Please check your code for this.

Conclusion

In this article, we discussed where the ‘str’ object is not callable error can occur and how we can resolve it. This is an easy error to fix. We must ensure we don’t use the reserved keywords for naming variables. In addition, we also have to avoid redefining default methods.

Trending Python Articles

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

Mistakes are easily made when you are naming variables. One of the more common mistakes is calling a variable “str”. If you try to use the Python method with the same name in your program,  “typeerror: ‘str’ object is not callable” is returned.

In this guide, we talk about what the Python error means and why it is raised. We walk through two examples of this error in action so you learn how to solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

The Problem: typeerror: ‘str’ object is not callable

Our error message is a TypeError. This tells us we’re trying to execute an operation on a value whose data type does not support that specific operation.

Take a look at the rest of our error message:

typeerror: 'str' object is not callable

When you try to call a string like you would a function, an error is returned. This is because strings are not functions. To call a function, you add () to the end of a function name.

This error commonly occurs when you assign a variable called “str” and then try to use the str() function. Python interprets “str” as a string and you cannot use the str() function in your program.

Let’s take a look at two example scenarios where this error has occurred.

Example Scenario: Declaring a Variable Called “str”

We write a program that calculates how many years a child has until they turn 18. We then print this value to the console.

Let’s start by collecting the current age of the young person by using an input() statement:

str = input("What is your age? ")

Next, we calculate how many years a young person has left until they turn 18. We do this by subtracting the value a user has given our program from 18:

years_left = 18 - int(str) 

We use the int() method to convert the age integer. This allows us to subtract the user’s age from 18.

Next, we convert this value to a string and print it to the console. We convert the value to a string because we need to concatenate it into a string. To do so, all values must be formatted as a string.

Let’s convert the value of “years_left” and print it to the console:

years_left = str(years_left)
print("You have " + years_left + " years left until you turn 18.")

This code prints out a message informing us of how many years a user has left until they turn 18. Run our code and see what happens:

What is your age? 7
Traceback (most recent call last):
  File "main.py", line 5, in <module>
	years_left = str(years_left)
TypeError: 'str' object is not callable

Our code returns an error. We have tried to use the str() method to convert the value of “years_left”. Earlier in our program, we declared a variable called “str”. Python thinks “str” is a string in our program, not a function.

To solve this error, we rename the variable “str” to “age”:

age = input("What is your age? ")
years_left = 18 - int(age) 
years_left = str(years_left)
print("You have " + years_left + " years left until you turn 18.")

As we have renamed our variable, Python will use the str() function when we call it. There is no longer a variable occupying that name. Let’s run our code again:

What is your age? 7
You have 11 years left until you turn 18.

Our code successfully calculates how many years a young person has left until they turn 18.

Example Scenario: String Formatting Using %

This error is also caused by a mistake in string formatting.

Let’s add a few new features to our last program. First, we ask a user for their name. Second, we’re going to craft the message that tells a user how many years they have left until they turn 18 using the % formatting syntax.

Begin by asking a user for their name:

name = input("What is your name? ")

Next, we revise our print() statement to use the % string formatting syntax. We do this because the % syntax is easier to read when formatting multiple values into a string. Here is the code we use to format the message we will show a user:

print("%s, you have %s years left until you turn 18."(name, age))

Our final program looks like this:

name = input("What is your name? ")
age = input("What is your age? ")

years_left = 18 - int(age) 
years_left = str(years_left)

print("%s, you have %s years left until you turn 18."(name, age))

Our code replaces the string type %s symbol with the values “name” and “age”, respectively. Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
	print("%s, you have %s years left until you turn 18."(name, age))
TypeError: 'str' object is not callable

Our code returns an error because we have forgotten to use the % operator to separate our string and the values we want to add to our string.

Our code thinks we are trying to call “%s, you have %s years left until you turn 18.” as a function because the string is followed by parenthesis.

To solve this error, we add a percentage sign between “%s, you have %s years left until you turn 18.” and (name, age) in our code:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

print("%s, you have %s years left until you turn 18." % (name, age))

This revision fixes the error:
What is your name? Alex
What is your age? 7
Alex, you have 11 years left until you turn 18.

Conclusion

The “typeerror: ‘str’ object is not callable” error is raised when you try to call a string as a function. To solve this error, make sure you do not use “str” as a variable name.

If this does not solve the problem, check if you use the % operator to format strings. A % sign should appear between a string and the values into which you want to add to a string.

Now you’re ready to solve this common Python error like a pro!

Понравилась статья? Поделить с друзьями:
  • Stormgame win64 shipping exe ошибка
  • Storehouse 4 сервер остановлен вследствие неустранимой ошибки
  • Store произошла ошибка что это
  • Store data structure corruption win 10 ошибка
  • Storage executive crucial ошибка микропрограммы