2015-06-11 45 views
0

我使用的是Python的字符串製作的HTML電子郵件,像這樣解:Python的ValueError異常:值過多與字符串格式化

 # Code setting up the message html 
     message = "long html message string" 

     scoped = "" 
     if settings.DEBUG: 
      scoped = "scoped" 

     header = """                 
      <style %s type='text/css'>            
       @media only screen and (max-width: 480px){       
        .emailImage{              
         height:auto !important;          
         max-width:200px !important;         
         width: 100% !important;          
        }                
       }                 
      </style>                 
      """ % scoped 
     footer = "html message footer" 

     message = header + message + footer 

     # Code sending the message. 

的問題是,上面的代碼給我的錯誤ValueError: too many values to unpack。但是,如果我從消息中刪除scoped變量,則html將運行,即,這可以工作(雖然不需要將範圍變量添加到我的HTML中)。

 # Code setting up the message html 
     message = "long html message string" 

     header = """                 
      <style type='text/css'>            
       @media only screen and (max-width: 480px){       
        .emailImage{              
         height:auto !important;          
         max-width:200px !important;         
         width: 100% !important;          
        }                
       }                 
      </style>                 
      """ 
     footer = "html message footer" 

     message = header + message + footer 

     # Code sending the message. 

爲什麼第一個版本拋出該錯誤,我該如何解決ValueError?

+0

你爲什麼要通過字符串替換建立HTML?這是模板的用途。 –

回答

4

你有width元素之後的轉義%符號,再添%逃脫它:

header = """                 
     <style %s type='text/css'>            
      @media only screen and (max-width: 480px){       
       .emailImage{              
        height:auto !important;          
        max-width:200px !important;         
        width: 100%% !important;          
       }                
      }                 
     </style>                 
     """ % scoped 

注意,當你擺脫了% scoped的,你不再是格式化字符串和%字符不再特別。

+0

是的!我以前曾試着用'\%'來逃避它,但這不起作用 - 在這種情況下你必須使用另一個'%'來轉義? – YPCrumble

+0

是的,在舊的格式中,它與C'printf'非常相似,你也可以在另一個'%' –

相關問題