【问题标题】:what does %(parameter)s means here%(parameter)s 在这里是什么意思
【发布时间】:2021-03-16 14:15:17
【问题描述】:

我有一个这样的代码 sn-p。我对 %()s 的使用感到困惑。 如果用于格式化参数, 我们不应该使用 %(threshold)d 作为阈值,因为它是一个数字吗?

def recommendations_for_user(user_id, threshold=4.5):
  # Join with the courses table
  query = """
  SELECT title, rating FROM recommendations
    INNER JOIN courses ON courses.course_id = recommendations.course_id
    WHERE user_id=%(user_id)s AND rating>%(threshold)s
    ORDER BY rating DESC
  """
  # Add the threshold parameter
  predictions_df = pd.read_sql(query, db_engine, params = {"user_id": user_id, 
                                                           "threshold": threshold})
  return predictions_df.title.values

# Try the function you created
print(recommendations_for_user(12, 4.65))

【问题讨论】:

  • 这不是(仅)SQL。 Edit 问题并标记宿主语言和/或框架。
  • 您使用的是哪个 dbms?

标签: python sql wildcard


【解决方案1】:

%(threshold)s 和 %(threshold)d 会做同样的事情,但 %(threshold)d 只会强制格式化。

%s 将调用 str(arg),而 %d 将在调用 str() 之前调用 int(arg)。

所以对于 %d 它将是 str(int(arg)) 如果 arg 不是有效数字,则会导致错误。 %s 不会引发任何错误。

因此,如果您确定阈值始终是有效数字,则可以使用 %(threshold)s。

【讨论】:

  • 如果此答案对您有帮助,请点击绿色复选标记接受,以便将此问题标记为已回答。
猜你喜欢
  • 1970-01-01
  • 2011-07-25
  • 2021-04-14
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多