Python3:不支持+:“float”和“str”的操作数类型

2024-04-24 07:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在我的代码中给大数字加逗号。当我隔离代码时,它可以工作:

num = str(12354343)
print("{:,}".format(float(num)))

但在我的代码中,我收到了不支持的+操作数类型错误:“float”和“str”。你知道吗

def commafy(x):
    x = "{:,}".format(float(x))
    return x

i=1

d = resp.json()
for result in d['results']:
    #print(result['campaign_name'])
    data[i] = {'Source': 'Taboola', 'Campaign': result['campaign_name'], 'Impr.': commafy(result['impressions']), 'CTR': round(result['ctr'],2) + "%", 'Spent': result['spent']}
    i+=1

这里怎么了?你知道吗

谢谢你


Tags: 代码nameformat类型def错误数字result
1条回答
网友
1楼 · 发布于 2024-04-24 07:41:05

你的问题在别处:

'CTR': round(result['ctr'],2) + "%",

round的结果是一个float,您试图将它与'%'合并,后者是一个字符串。你知道吗

您不是在这里commafy处理浮点结果。。。你知道吗

'CTR': f"{round(result['ctr'],2)}%", # should work for 3.6+ (string interpolation syntax)

或者

'CTR': "{}%".format(round(result['ctr'],2)), # should work for below 3.6

相关问题 更多 >