@sashka_zaharov2001

Как исправить ошибку TypeError: bad operand type for unary +: 'str'?

У меня есть такой код(выдает температуру по дням через Yahoo):
import pprint
import requests
from dateutil.parser import parse


class YahooWeatherForecast():

    def get(self, city):
        url = f"https://query.yahooapis.com/v1/public/yql?q="
        + f"select%20*%20from%20weather.forecast%20where%20w"
        + f"oeid%20in%20(select%20woeid%20from%20geo.places("
        + f"1)%20where%20text%3D%22{city}%22)%20and%20u%3D%2"
        + f"7c%27&format=json&env=store%3A%2F%2Fdatatables.o"
        + f"rg%2Falltableswithkeys"
        data = requests.get(url).json()
        forecast_data = data["query"]["results"]["channel"]["item"]["forecast"]
        forecast = []
        for day_data in forecast_data:
            forecast.append({
                "date": parse(day_data["date"]),
                "high_temp": day_data["high"]
            })
        return forecast


class City_Info:

    def __init__(self, city, weather_forecast=None):
        self.city = city
        self._weather_forecast = weather_forecast or YahooWeatherForecast()

    def weather_forecast(self):
        return self._weather_forecast.get(self.city)


def _main():
    city_info = City_Info("Moscow")
    forecast = city_info.weather_forecast()
    pprint.pprint(forecast)

if __name__ == "__main__":
        _main()

И вот сама ошибка:
Traceback (most recent call last):
File "c:\Users\Admin\P_Ground\city.py", line 42, in
_main()
File "c:\Users\Admin\P_Ground\city.py", line 38, in _main
forecast = city_info.weather_forecast()
File "c:\Users\Admin\P_Ground\city.py", line 33, in weather_forecast
return self._weather_forecast.get(self.city)
File "c:\Users\Admin\P_Ground\city.py", line 10, in get
+ f"select%20*%20from%20weather.forecast%20where%20w"
TypeError: bad operand type for unary +: 'str'
  • Вопрос задан
  • 3829 просмотров
Пригласить эксперта
Ответы на вопрос 2
Xaip
@Xaip
Неправильной перенос строки как минимум
url = f"https://query.yahooapis.com/v1/public/yql?q="\
              + f"select%20*%20from%20weather.forecast%20where%20w" \
              + f"oeid%20in%20(select%20woeid%20from%20geo.places("\
              + f"1)%20where%20text%3D%22{city}%22)%20and%20u%3D%2" \
              + f"7c%27&format=json&env=store%3A%2F%2Fdatatables.o" \
              + f"rg%2Falltableswithkeys"

И зачем вы создали такое количество строк? Вы буквально создали 6 строк и сконкатенировали их. Если вы так хотите воспользоваться новой фичой - то используйте многострочный комментарик url = f"""String {city} """
Ответ написан
Комментировать
@ariezzz_python
Конкратенацию строк явно указывать вообще не обязательно. можно сделать так:
url = "https://query.yahooapis.com/v1/public/yql?q="\
"select%20*%20from%20weather.forecast%20where%20w" \
"oeid%20in%20(select%20woeid%20from%20geo.places("\
f"1)%20where%20text%3D%22{city}%22)%20and%20u%3D%2" \
"7c%27&format=json&env=store%3A%2F%2Fdatatables.o" \
"rg%2Falltableswithkeys"
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы