简体   繁体   中英

Formatting a variable as a string

I am trying to create a Python program that will query a URL and produce a JSON file. I need to pass an argument in the end of the URL which comes from the SQL query.

I have imported the requests library.

I get an error message 'TypeError: float argument required, not str' when I am trying to pass argument in the URL.

There is only one column of result produced from the query:

id   
2
3
4

Below is what I came up with:

import MySQLdb
import requests

con=MySQLdb.connect(host="localhost",user="test", passwd="test", db ="mfg")
cur = con.cursor()
select=("select id from tblMfg")

cur.execute(select)
result=cur.fetchall()
for i in result:
    col =i[0]
    col1=str(col)
    url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1&paramid=%d' % col1
    user = 'abc'
    password ='testgo'
    data = requests.get(url, auth=(user, password))
    json_data=data.json()
    print json_data

Leave creating parameters to the requests framework instead:

params = {'solution': 'nd', 'path': '', 'file': 'Test.nd', 'dataAccessId': '1',
          'paramid': str(col[0])}
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery'
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password), params=params)

The error message 'TypeError: float argument required, not str' also occurs when you try to format a string containing an (accidental) naked percent sign.
Example:

>>> print "fail 100% for serverid|%s| " % ("a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float argument required, not str
>>>

The "f" after the "100% " is interpreted as asking for a floating point argument, whereas it was simply my smudgefingers leaving off the second percent sign.

>>> print "fail 100%% for serverid|%s| " % ("a")
fail 100% for serverid|a|
>>>

works fine. If the word following the "100% " begins with d or o or s, you get slightly different error messages.

I was unlucky enough to have this happen several call layers inside a 2-nested try-except, so the error showed up a mile away from the line that caused it.

print ("float_value : %f , digit_value : %d , string_value : %s"  % (3.4, 5, 'somestring'))
float_value : 3.400000 , digit_value : 5 , string_value : somestring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM