Typeerror str object is not callable ошибка

Вы сталкиваетесь с разочаровывающим сообщением об ошибке в своем коде Python, в котором говорится: «TypeError: объект ‘str’ не вызывается»? Это сообщение об ошибке указывает на то, что вы пытаетесь вызвать строковый объект, как если бы он был функцией, но строки не могут быть вызваны. Эта ошибка может возникать по разным причинам, включая синтаксические ошибки, неправильные типы данных и неправильное форматирование. В этом сообщении блога мы рассмотрим возможные причины ошибки «TypeError: ‘str’ object is not callable» и способы ее исправления в Python.

Прежде чем мы углубимся в причины и решения ошибки «TypeError: ‘str’ object is not callable», давайте сначала разберемся, что означает объект ‘str’ в Python. В Python объект ‘str’ представляет собой последовательность символов Unicode, которую можно создать, заключив символы в одинарные или двойные кавычки. Например,

name="Python"

Войти в полноэкранный режимВыйти из полноэкранного режима

Здесь переменной «имя» присваивается объект «str», который содержит символы Unicode «Python».

Мы можем применять различные строковые методы для управления и форматирования объекта ‘str’ в Python. Например, мы можем использовать метод «capitalize()», чтобы сделать первую букву объекта «str» прописной:

name="python"
capitalized_name = name.capitalize()
print(capitalized_name) # Output: 'Python'

Войти в полноэкранный режимВыйти из полноэкранного режима

Причины TypeError: объект ‘str’ не вызывается в Python

Сообщение об ошибке «TypeError: ‘str’ object is not callable» может возникать по разным причинам, перечисленным ниже:

1. Неправильный синтаксис

Одной из наиболее распространенных причин ошибки «TypeError: ‘str’ object is not callable» является неправильный синтаксис в коде. Синтаксическая ошибка возникает, когда интерпретатор Python не может проанализировать код из-за ошибок в синтаксисе. Например, рассмотрим следующий фрагмент кода:

result = "Hello"()

Войти в полноэкранный режимВыйти из полноэкранного режима

Этот код вызовет сообщение об ошибке «TypeError: ‘str’ object is not callable», поскольку мы пытаемся вызвать ‘str’-объект «Hello», как если бы это была функция. Правильный синтаксис для назначения объекта ‘str’ переменной без круглых скобок:

result = "Hello"

Войти в полноэкранный режимВыйти из полноэкранного режима

2. Неправильный тип данных

Другая распространенная причина ошибки «TypeError: объект ‘str’ не может быть вызван» — это когда мы пытаемся вызвать объект ‘str’, как если бы он был функцией, из-за ошибки типа данных. Например, рассмотрим следующий фрагмент кода:

name="Python"
result = name(5)

Войти в полноэкранный режимВыйти из полноэкранного режима

Здесь мы пытаемся вызвать объект «str» «Python» с аргументом 5, как если бы это была функция. Поскольку строки не вызываются, мы получим сообщение об ошибке «TypeError: ‘str’ object is not callable». Чтобы исправить эту ошибку, нам нужно убедиться, что мы вызываем функции с правильными типами данных.

3. Неправильное форматирование

Неправильная ошибка форматирования также может вызвать ошибку «TypeError: ‘str’ object is not callable». Например, рассмотрим следующий фрагмент кода:

name="Python"
result = name.capitalize

Войти в полноэкранный режимВыйти из полноэкранного режима

Здесь мы пытаемся присвоить строковый метод «capitalize» переменной «result», но забыли использовать круглые скобки после имени метода. Правильный способ вызвать метод «capitalize» — использовать круглые скобки:

name="Python"
result = name.capitalize()

Войти в полноэкранный режимВыйти из полноэкранного режима

Как исправить TypeError: объект ‘str’ не вызывается в Python

Теперь, когда у нас есть общее представление о причинах ошибки «TypeError: ‘str’ object is not callable», давайте рассмотрим некоторые возможные решения для исправления этой ошибки в Python:

1. Проверьте наличие синтаксических ошибок

Первый шаг к исправлению ошибки «TypeError: ‘str’ object is not callable» — перепроверить синтаксис кода. Убедитесь, что вы правильно использовали скобки, кавычки и другие символы в нужных местах. Проверьте наличие отсутствующих или лишних скобок, квадратных скобок или запятых в коде.

2. Проверьте наличие ошибок типа данных

Убедитесь, что при назначении и вызове функций в коде используется правильный тип данных. Если вы пытаетесь вызвать функцию для строкового объекта, вы получите сообщение об ошибке «TypeError: ‘str’ object is not callable». Поэтому убедитесь, что вызов функции действительно действителен для используемого типа данных.

3. Проверьте на ошибки форматирования

Дважды проверьте, чтобы вызовы методов в вашем коде включали соответствующие круглые скобки, даже для методов, которые не принимают никаких аргументов. Убедитесь, что вы используете правильные соглашения об именах для функций и методов.

4. Проверьте наличие глобальных пространств имен

Иногда пространство имен глобального метода совпадает с именем локальной переменной, что может вызвать проблемы. Этого можно избежать, задав совершенно новое имя для созданной переменной.

5. Переименуйте переменные

Иногда мы по ошибке создаем имя переменной, совпадающее с именем метода в том же коде. Это вызывает проблемы, так как скрывает метод за переменной и может привести к ошибкам позже. Если вы переименуете переменную, метод может быть вызван снова в будущем.

Заключение

Сообщение об ошибке «TypeError: ‘str’ object is not callable» может быть вызвано синтаксическими ошибками, ошибками типа данных, ошибками форматирования и неправильно определенными переменными. Прочитав этот пост в блоге, вы должны хорошо понимать, почему эта ошибка возникает во время программирования на Python и как ее устранить. Не забудьте дважды проверить синтаксис, типы данных и форматирование, чтобы избежать этой ошибки в будущем. Если вы по-прежнему не можете устранить ошибку, обратитесь к документации по Python или обратитесь за помощью к опытным разработчикам.

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

В этой строке вы переписываете имя input и теперь в ней будет строка, которую введет пользователь, а не функция input:

input = str(input("Введите Ваш пол по цифре сверху: "))

Поэтому, при последующем вызове input, например в height = str(input("Введите Ваш рост(в сантиметрах): ")) будет та ошибка

Решение. Назовите по другому переменную для input


UPD.

Исправил код из вопроса:

def check():
    global sex, height1, weight1, height2, weight2

    print("1.Мальчик")
    print("2.Девочка")

    sex = input("Введите Ваш пол по цифре сверху: ")
    if sex == "1":
        height1 = input("Введите Ваш рост(в сантиметрах): ")
        weight1 = input("Введите Ваш вес: ")

    elif sex == "2":
        height2 = input("Введите Ваш рост(в сантиметрах): ")
        weight2 = input("Введите Ваш вес: ")

    else:
        print("Введите одну из цифр выше!")


sex, height1, weight1, height2, weight2 = ' ' * 5

check()

print(sex, height1, weight1, height2, weight2)

This error occurs when you try to call a string as if it were a function. This error can occur if you override the built-in str() function or you try to access elements in a string using parentheses instead of square brackets.

You can solve this error by ensuring you do not override the str() function or any function names. For example:

my_str = 'Python is fun!'

my_int = 15

my_int_as_str = str(15)

If you want to access elements in a string, use square brackets. For example,

my_str = 'Python is fun!'

first_char = my_str[0]

This tutorial will go through the error in detail, and we will go through an example to learn how to solve the error.

Table of contents

  • TypeError: ‘str’ object is not callable
    • What is a TypeError?
    • What does Callable Mean?
  • Example #1: Using Parenthesis to Index a String
    • Solution
  • Example #2: String Formatting Using
    • Solution
  • Example #3: Using the Variable Name “str”
    • Solution
  • Summary

TypeError: ‘str’ object is not callable

What is a TypeError?

TypeError tells us that we are trying to perform an illegal operation for a specific Python data type.

What does Callable Mean?

Callable objects in Python have the __call__ method. We call an object using parentheses. To verify if an object is callable, you can use the callable() built-in function and pass the object to it. If the function returns True, the object is callable, and if it returns False, the object is not callable.

Let’s test the callable() built-in function with a string:

string = "research scientist"

print(callable(string))
False

We see that callable returns false on the string.

Let’s test the callable() function with the square root method from the math module:

from math import sqrt

print(callable(sqrt))
True

We see that callable returns True on the sqrt method. All methods and functions are callable objects.

If we try to call a string as if it were a function or a method, we will raise the error “TypeError: ‘str’ object is not callable.”

Example #1: Using Parenthesis to Index a String

Let’s look at an example of a program where we define a for loop over a string:

string = "research scientist"

for i in range(len(string)):

    print(string(i))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 for i in range(len(string)):
      2     print(string(i))
      3 

TypeError: 'str' object is not callable

To index a string, you have to use square brackets. If you use parentheses, the Python interpreter will treat the string as a callable object. Strings are not callable. Therefore you will raise the error “TypeError: ‘str’ object is not callable”.

Solution

We need to replace the parentheses with square brackets to solve this error.

string = "research scientist"

for i in range(len(string)):

    print(string[i])
r
e
s
e
a
r
c
h
 
s
c
i
e
n
t
i
s
t

The code runs with no error and prints out each character in the string.

Example #2: String Formatting Using

The TypeError can also occur through a mistake in string formatting. Let’s look at a program that takes input from a user. This input is the price of an item in a store with a seasonal discount of 10%. We assign the input to the variable price_of_item. Then we calculate the discounted price. Finally, we can print out the original price and the discounted price using string formatting.

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

With string formatting, we can replace the %s symbols with the values price_of_item and rounded_discounted_price. Let’s see what happens when we try to run the program.

Enter the price of the item17.99

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

TypeError: 'str' object is not callable

The code returns an error because we forgot to include the % operator to separate the string and the values we want to add to the string. The Python interpreter tries to call ‘The original price was %s, the price after 10% discount is %s‘ because the string has parentheses following it.

Solution

To solve this error, we need to add the % between the string

‘The original price was %s, the price after the discount is %s‘ and (price_of_item, rounded_discounted_price)

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'%(price_of_item, rounded_discounted_price))
Enter the price of the item17.99

The original price was 17.99, the price after the discount is 16.19

The code successfully prints the original price and the rounded price to two decimal places.

Example #3: Using the Variable Name “str”

Let’s write a program that determines if a user is too young to drive. First, we will collect the current age of the user using an input() statement. If the age is above 18, the program prints that the user is old enough to drive. Otherwise, we calculate how many years are left until the user can drive. We use the int() method to convert the age to an integer and then subtract it from 18.

Next, we convert the value to a string to print to the console. We convert the value to a string because we need to concatenate it to a string.

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

if int(str) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(str)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + ' year(s) left')


Let’s see what happens when we run the program:

What is your age? 17

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      3 else:
      4     years_left = 18 - int(str)
      5     years_left = str(years_left)
      6     print('You are not old enough to drive, you have ' + years_left + ' year(s) left')
      7 

TypeError: 'str' object is not callable

We raise the error “TypeError: ‘str’ object is not callable” because we tried to use the str() method to convert the integer value years_left. However, earlier in the program we declared a variable called “str“. From that point on, the Python interpreter sees “str” as a string in the program and not a function. Therefore, when we try to call str() we are instead trying to call a string.

Solution

To solve this error, we need to rename the user input to a suitable name that describes the input. In this case, we can use “age“.

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

if int(age) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(age)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + 'year(s) left')

Now we have renamed the variable, we can safely call the str() function. Let’s run the program again to test the outcome.

What is your age? 17

You are not old enough to drive, you have 1 year(s) left

The code runs and tells the user they have 1 year left until they can drive.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on the ‘not callable’ TypeError, go to the article: How to Solve Python TypeError: ‘module’ object is not callable.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

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:\Projects\Tryouts\listindexerror.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:\Projects\Tryouts\listindexerror.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:\Projects\Tryouts\listindexerror.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.

Понравилась статья? Поделить с друзьями:
  • Typeerror nonetype object is not subscriptable python ошибка
  • Typeerror module object is not callable питон ошибка
  • Typeerror int object is not iterable ошибка
  • Typeerror int object is not callable ошибка
  • Typeerror function object is not subscriptable ошибка