2017-08-28 89 views
1

我試圖用%s將文本插入到大型網址中。每當我運行它,我得到的錯誤:TypeError: a float is required這似乎很愚蠢,因爲我把字符串放入字符串,並沒有浮動或整數涉及。任何幫助都是極好的!我的代碼是低於格式化字符串(%s)返回TypeError:需要浮點數

import datetime 

date = (datetime.datetime.today().date() - datetime.timedelta(days=100)).strftime("%m/%d/%Y") 
date = str(date) 
date = date.replace("/","%2F") 

def genUrl(account, date, lastName, firstName): 
    url = "https://arpmp-ph.hidinc.com/arappl/bdarpdmq/pmqadhocrpt.html?a=&page=recipqry&disp-bdate=%s&disp-edate=%s&recip-list=02685245&output=web&dt-sort-by=rcpdt&mode=Recipient_Query&w_method=POST&suplist=BM0650386&base-prsb=0&base-phrm=0&base-recip=1&tot-recip=1&report=PHY&recip-sex=A&recip-dob=01%2F21%2F1964&account-id=%s&date=%s&dob-days=0&recip-name=%s&recip-fname=%s&enum-read-cnt=2&enum-keep-cnt=1&etime=5&pagename=pmqrecipqry&pdmdir=arpdm&pdmstate=ar&scriptname=%2Farappl%2Fbdarpdmq&exprecip=yes" %(date, str(datetime.datetime.now()), account, date, lastName, firstName) 
    print(url) 

genUrl("example",date, "Smith", "Jogn") 

對不起,如果我只是犯了一個愚蠢的錯誤,沒有注意到它。我對Python比較陌生

+0

旁白:你可能想'html.escape'(在舊版本的Python或'cgi.escape')。 – o11c

+4

你的url包含'%2F',它看起來像一個float的Python字符串格式化語法。如果你不想把它們解釋爲python字符串格式,你需要將字符串中的任何'%'符號轉義爲'%%'。 – larsks

+1

請注意,有很多*更好的方式來操縱URL位比原始字符串操作。看看所有的'urllib.parse'類/函數。 – o11c

回答

5

它是因爲你用"%2F"代替"/",它是浮點的Python佔位符。

Use .format() instead of %

import datetime 

date = (datetime.datetime.today().date() - datetime.timedelta(days=100)).strftime("%m/%d/%Y") 
date = str(date) 
date = date.replace("/","%2F") 

def genUrl(account, date, lastName, firstName): 
    url = "https://arpmp-ph.hidinc.com/arappl/bdarpdmq/pmqadhocrpt.html?a=&page=recipqry&disp-bdate={}&disp-edate={}&recip-list=02685245&output=web&dt-sort-by=rcpdt&mode=Recipient_Query&w_method=POST&suplist=BM0650386&base-prsb=0&base-phrm=0&base-recip=1&tot-recip=1&report=PHY&recip-sex=A&recip-dob=01%2F21%2F1964&account-id={}&date={}&dob-days=0&recip-name={}&recip-fname={}&enum-read-cnt=2&enum-keep-cnt=1&etime=5&pagename=pmqrecipqry&pdmdir=arpdm&pdmstate=ar&scriptname=%2Farappl%2Fbdarpdmq&exprecip=yes".format(date, str(datetime.datetime.now()), account, date, lastName, firstName) 
    print(url) 

genUrl("example",date, "Smith", "Jogn") 
+0

這不是替代品,它是其他硬編碼的,沒有人願意閱讀的大長字符串。 – o11c