pythin脚本中的TypeError

2024-09-27 00:15:55 发布

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

运行下面的python脚本时,出现错误。有人能帮忙吗

query1 = "SELECT Date AS \"time\",jobType,sum(CJob) AS \"sum(CJob)\" FROM logs WHERE Date = '06/01/2021' and jobType is not null GROUP BY jobType ORDER BY Date"

mycursor.execute(query1)
myresult1 = mycursor.fetchone()
print("Total Completed orders in Logs Table(New DB)                             :%s  " % myresult1)

下面是一个错误

File "C:\Users\santhosh.mohana\python_scripts\clow.py", line 35, in <module>
    print("Total Completed orders in Logs Table(New DB)                             : %s " % myresult1)
TypeError: not all arguments converted during string formatting

当我将它保留为%d时,我得到了这个

File "C:\Users\santhosh.mohana\python_scripts\clow.py", line 35, in <module>
    print("Total Completed orders in Logs Table(New DB)                             : %d " % myresult1)
TypeError: %d format: a number is required, not str

Tags: innewdbdate错误tablenottotal
1条回答
网友
1楼 · 发布于 2024-09-27 00:15:55

myresult的内容不是字符串,更可能是int类型。%s格式化程序需要一个字符串。有两种方法可以巧妙地解决这个问题

最快的方法是在使用变量之前进行快速转换:

#... 
print("Total Completed orders in Logs Table(New DB) :%s  " % str(myresult1))

或者,我喜欢新的字符串f字符串格式,它允许将变量(locals)直接注入字符串:

#... 
print(f"Total Completed orders in Logs Table(New DB) :{myresult1}")

不需要转换,因为它在变量中使用标准__str____repr__

这里有一些很好的信息:https://realpython.com/python-f-strings/

相关问题 更多 >

    热门问题