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

Ihechikara Vincent Abba

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.
Python-сообщество
![]()
- Начало
- » Python для новичков
- » Ошибка ‘str’ object is not callable Что не так?
#1 Июль 10, 2021 08:36:39
moonhyde96 Зарегистрирован: 2021-07-10 Сообщения: 1 Репутация: 0 Профиль Отправить e-mail
Ошибка ‘str’ object is not callable Что не так?
for i in x:
if x.count(i)==1:
result.append(i)
print(result)
Почему-то выбивает ошибку: ‘str’ object is not callable
Объясните, пожалуйста, что не так и как это исправить?
Отредактировано moonhyde96 (Июль 10, 2021 08:37:12)
#2 Июль 10, 2021 09:54:27
Ocean Зарегистрирован: 2021-03-14 Сообщения: 131 Репутация: 9 Профиль Отправить e-mail
Ошибка ‘str’ object is not callable Что не так?
moonhyde96
Ты пытаешься со строкой, работать как с функцией, поэтому возникает TypeError
чтобы ее исправить надо использовать правильный тип данных
так же обрати внимание, что когда ты вставляешь код программы без тегов, то не сохраняются отступы, квадратные скобки и прочее. Вот в x и result у тебя че было?) Что вообще программа должна делать?
Используй теги и тебе охотнее помогут.
x= [1, 2, 3, 3, 4, 4] result = [] for i in x: if x.count(i) == 1: result.append(i) print(result)
x= 'ddjkffh' result = [] for i in x: if x.count(i) == 1: result.append(i) print(result)
Все работает и result отдает элементы, которые в х встречаются только один единственный раз
Отредактировано Ocean (Июль 10, 2021 10:01:35)
TypeError: ‘str’ object is not callable
Возможно, создан класс у которого есть атрибут типа str , и при этом метод с таким же названием как и у атрибута. При попытке вызова метода Python понимает, что он существует, но получает указатель не на метод а на str.
Решение этой проблемы с помощью декоратора описано в статье Python ООП: декоратор property
Подробнее про тип данных str вы можете прочитать здесь
Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых
TypeError: ‘str’ object is not callable?
Консоль выдаёт:
D:\python>python weather.py
Узнайте погоду и время в своём городе
В каком городе вы живёте?: Тольятти
Traceback (most recent call last):
File «D:\python\weather.py», line 20, in
print(«В городе » + place + » сейчас» + str(w.detailed_status()))
TypeError: ‘str’ object is not callable
Я пробовал делать с str вот так :
print("В городе " + place + " сейчас" + str(w.detailed_status()))
В чем моя ошибка? Вот ссылка на сервис у которого прошу погоду https://github.com/csparpa/pyowm
- Вопрос задан более трёх лет назад
- 7278 просмотров