【问题标题】:Formatting strings (%s) returns TypeError: a float is required格式化字符串 (%s) 返回类型错误:需要浮点数
【发布时间】:2017-08-28 02:33:26
【问题描述】:

我正在尝试使用 %s 将文本插入到大网址中。每当我运行它时,我都会收到错误:TypeError: a float is required 这似乎很愚蠢,因为我将字符串放入字符串中并且不涉及浮点数或整数。任何帮助都是极好的!我的代码如下

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 比较陌生

【问题讨论】:

  • 旁白:你可能想要html.escape(或者在旧的python版本中是cgi.escape)。
  • 你的 url 包含 %2F 看起来像 Python 字符串格式化语法的浮点数。如果您不希望将字符串中的任何% 符号转义为%%,则需要将它们解释为python 字符串格式。
  • 请注意,与原始字符串操作相比,有 很多 更好的方法来操作 URL 位。查看所有urllib.parse 类/函数。
  • 正如@larsks 所说,当Python 进行字符串替换时,您将替换为 %2F 浮点声明。另外,我强烈建议在 Python 3.x 中使用字符串插值或 .format() 而不是字符串格式
  • 这个网站上的花生画廊有什么问题 - 为什么这个问题值得一票否决?当然,这可能是一个卑微的问题,但来吧。

标签: python string python-3.x string-formatting


【解决方案1】:

这是因为您将 "/" 替换为 "%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")

【讨论】:

  • 不是替代品,而是大长串中没有人愿意阅读的其他硬编码。
猜你喜欢
  • 2018-01-11
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多