【问题标题】:How do I change the URL depending on the number of items in input list如何根据输入列表中的项目数更改 URL
【发布时间】:2021-12-15 08:55:03
【问题描述】:

我正在使用 API,我需要构建一个 URL 来检索我被询问的信息。该函数的参数是一个包含不同国家代码的列表。 URL 的基本格式是https://restcountries.com/v2/alpha?codes={code},{code},{code},每个代码都来自参数列表。但是,列表中的项目数量可能会有所不同,那么如何使用适当数量的代码构建 url?

例如: 如果列表是 ["kor", "usa", "de"],则 URL 应类似于 https://restcountries.com/v2/alpha?codes=kor,usa,de

【问题讨论】:

  • 使用",".join(codes)

标签: python api url


【解决方案1】:
def createUrl(codes):
    url = " https://restcountries.com/v2/alpha?codes="
    for i, code in enumerate(codes):
        url += code
        if i != len(codes)-1: url += ","
    return url

对于输入['foo','bar','baz'],这段代码将产生https://restcountries.com/v2/alpha?codes=foo,bar,baz

【讨论】:

  • 更好用url += ",".join(codes)
  • @eyllanesc 不错,更优雅
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 2013-04-17
  • 1970-01-01
  • 2016-02-26
相关资源
最近更新 更多