Tamilselvan
Tamilselvan

Reputation: 55

TypeError in a Python script

While running the below python script, getting errors. can someone help?

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)

Getting this below error.

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

When i keep it as %d, i am getting this one

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

Upvotes: 1

Views: 67

Answers (1)

Glycerine
Glycerine

Reputation: 7347

The content of myresult is not a string but more-likely an int type. The %s formatter would like a string. There are two ways to neatly fix this.

The quickest is a fast conversion before you use the var:

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

Or alternatively, I love the new string f string formatting of which allows injection of variables (locals) straight into the string:

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

No convert required as it uses the standard __str__ or __repr__ in the variable.

Some nice info here: https://realpython.com/python-f-strings/

Upvotes: 1

Related Questions