2011-02-07 48 views
1

我正在使用Python進行某些操作,而且我需要從URL 20中的空間%20轉義出來。例如:從html跳轉%20

"%20space%20in%20%d--" % ordnum

所以我需要使用%20作爲URL,但是然後使用%d作爲數字。但是,我得到這個錯誤:

TypeError: not enough arguments for format string

我知道問題是什麼,我只是不知道如何從20%和逃生修復它。

+0

什麼是%運算符在這個片段中做什麼?不是Python用戶 - > – notJim 2011-02-07 21:50:42

+0

@notJim:相當於`sprintf(「%...」,ordnum)`在其他語言中 – Cameron 2011-02-07 21:53:03

回答

6

一種方法是將%字符翻番:

"%%20space%%20in%%20%d--" % ordnum 

但可能是更好的方法是使用urllib.quote_plus()

urllib.quote_plus(" space in %d--" % ordnum) 
4

的%20應該像%%時,Python的格式化看到20它。對於Python,%%格式化爲%。

1
>>> import urllib 
>>> unquoted = urllib.unquote("%20space%20in%20%d--") 
>>> ordnum = 15 
>>> print unquoted % ordnum 
space in 15-- 
0

我看到三種方式來解決這個問題:

  1. 逃離

    "%%%20dogs" % 11 
    
  2. 使用新.format語法。

    "{}%20dogs".format(11) 
    
  3. 使用,因爲我認爲這是可能的+號,而不是%20

    "%+dogs" % 11