0

我有一个已去除标点符号的城市列表,我需要正确格式化 URL。我的列表是 ['New', 'York', 'NY'] 和 ['Lansing', 'MI'] 我需要格式化查询,以便参数分配由 (&) 符号和城市中的单词分隔由 (+) 号分隔。

例如,它应该类似于 www.url.com/origin=New+York+NY&destination=Lansing+MI

4

1 回答 1

2

From the urllib docs:

Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string

So

urllib.parse.urlencode({
  'origin'      : ' '.join(['New', 'York', 'NY']),
  'destination' : ' '.join(['Lansing', 'MI'])
})

yields

'origin=New+York+NY&destination=Lansing+MI'

That documentation references the obsolete RFC 2396, but the differences between RFC 3986 and 2396 do not affect query string composition.

于 2013-04-15T20:48:46.487 回答