我正在使用一个url来获取给定城市的经纬度。当我经过的时候
“纽约”作为字符串它不会给出任何结果,但当我通过“纽约20分”时它做到了。如何将纽约式的单词传递给查询字符串?

current_location = 'New york' #not working
current_location2 = 'New%20York' # working
location_string = 'http://maps.googleapis.com/maps/api/geocode/json?address=' +current_location+ '&sensor=false'

最佳答案

使用urllib.quote()urllib.quote_plus()将字符替换为相应的%xx字符,或使用urllib.urlencode()从要进入URL的变量字典构造查询字符串。例子:

>>> import urllib
>>> urllib.quote('New York')
'New%20York'
>>> urllib.quote_plus('New York')
'New+York'
>>> urllib.urlencode({'address': 'New York', 'sensor': 'false'})
'sensor=false&address=New+York'

关于python - 查询字符串传递错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9000399/

10-11 15:03