2012-12-11 50 views
1

以下是按预期工作的代码块。使用if检查实例

for key in context: 
     if isinstance(context[key],collections.Iterable): 
      queryString += '%s=%s&' % (key, urllib.quote(context[key])) 
     else: 
      queryString += '%s=%s&' % (key, context[key]) 
    return queryString 

但我不明白使用if块。下面的工作不应该?

for key in context: 
    queryString += '%s=%s&' % (key, context[key]) 
return queryString 
+0

什么是'报价()'? –

+0

@SamMussmann我想'urllib.quote' –

+0

是的。它应该是urllib.quote – shantanuo

回答

3

它基本上是指“在转换为字符串表示时引用任何不是数字或序列的东西”。它逃避字符,使他们urlencoded。

if将阻止它引用int,float等,因为那些会崩溃quote功能。

context = {'a': 'a b c', 'b': ('a', '@', 'c'), 'c': 1} 
queryString = '' 

for key in context: 
    if isinstance(context[key],collections.Iterable): 
     queryString += '%s=%s&' % (key, urllib.quote(context[key])) 
    else: 
     queryString += '%s=%s&' % (key, context[key]) 

print queryString 
# a=a%20b%20c&c=1&b=a%40c& 

虽然它只有根据您的潜在投入可能(上下文的价值)有意义。它会碰撞说,一个整数列表。

不使用quote应该是这样的:

for key in context: 
    queryString += '%s=%s&' % (key, context[key]) 

# invalid url format 
# a=a b c&c=1&b=('a', '@', 'c')& 

和运行上的一切quote会导致:

for key in context: 
    queryString += '%s=%s&' % (key, urllib.quote(context[key])) 
... 
TypeError: argument 2 to map() must support iteration 
+0

这是否意味着non-iterables不能被“quote”d? – shantanuo