2012-01-25 109 views
1

我正在使用URL来获取给定城市的经度和纬度。当我通过 “纽约”作为字符串时,它不会给出任何结果,但是当我通过“新%20York”时,它就做到了。如何将纽约字样传递给查询字符串?查询字符串传递错误

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' 

回答

5

使用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' 
+0

是的我的坏,它真的工作 –