首页 > 解决方案 > Python:字符串连接类型错误 - 一元 + 的错误操作数类型:'str'

问题描述

我正在编写一个简单的函数来确定风向/风速。使用 Darksky Web API。试图打印一个包含两个变量的句子,速度和方向。

我尝试过将风速/方向变量设置为 ints、float 或 strs。

weather = forecast('api_key',lat, -long)
windbearing = weather.windBearing
windspeed = float(weather.windSpeed)

def windcompass(windbearing):
    val = int((windbearing/22.5)+.5)
    argument = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
    return argument[(val % 16)]

direction = windcompass(windbearing)

print('The wind is blowing ', + windspeed, + 'at ', + direction, + 'MPH')

我收到此错误

TypeError:一元+的错误操作数类型:'str'

标签: pythonpython-3.xstringconcatenation

解决方案


不要在打印功能中使用逗号:

print( str1 + str2 + ...)

您可能想先将ints/转换floatsstr

print(str(float_value) + str(int_value) + ...)

示例(您的代码):

print('The wind is blowing ' + str(windspeed) + ' at ' + str(direction) + ' MPH')

推荐阅读