2013-05-31 30 views
2

解決Python:爲什麼這個字符串無效?

我有這個字符串:

' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) 

但它一直給我一個語法錯誤。該行應該是這樣的bash相當於:

echo " ServerAlias ${hostOnly}.* www.${hostOnly}.*" >> $prjFile 

提個醒第一個字符串是myFile.write功能的一部分,但是這不是問題,我甚至不能得到字符串掙夠感覺它讓我運行程序。

回溯:

File "tomahawk_alpha.py", line 89 
    ' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) 
                 ^

但不管我怎麼改變這種狀況似乎'符號不工作。我究竟做錯了什麼?

針對@mgilson:

myFile = open(prjFile, 'w+') 
    myFile.write("<VirtualHost 192.168.75.100:80>" 
       " ServerName www.{hostName}".format(hostName=hostName) 
       ' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) 
       " DocumentRoot ", prjDir, "/html" 
       ' CustomLog "\"|/usr/sbin/cronolog /var/log/httpd/class/',prjCode,'/\{hostName}.log.%Y%m%d\" urchin"'.format(hostName=hostName) 
       "</VirtualHost>") 
    myFile.close() 

我在它自己的myFile.write行的每一行,但只生產了第一線,然後退出。所以我認爲只需調用它一次,並將其間隔即可創建預期結果。

"foo" "bar" 

結果"foobar"

但是,以下將不起作用:

+0

我沒有看到任何字符串錯誤。上一行是否關閉了所有括號? – mgilson

+0

在你的回溯中,它看起來像你刪除了錯誤類型。你可以包括這個,這樣我們可以更好地診斷問題? – SethMMorton

+0

問題可能出現在mgilson提到的前一行。你也應該檢查所有'''是否關閉。 – SethMMorton

回答

4

你有幾個語法錯誤。但是,您可能需要考慮使用三重引用的字符串 - 從長遠來看,修改起來要容易得多:

myFile.write("""<VirtualHost 192.168.75.100:80> 
       ServerName www.{hostName} 
       ServerAlias {hostNameshort}.* www.{hostNameshort}.* 
       DocumentRoot {prjDir}/html 
       CustomLog "\"|/usr/sbin/cronolog /var/log/httpd/class/{prjCode}/\{hostName}.log.%Y%m%d\" urchin" 
      </VirtualHost>""".format(hostName=hn, hostNameshort=hns, prjDir=prjd, prjCode=prjc)) 
+0

非常感謝! –

+0

這個功能奇妙,我將更經常地使用這個三重引用的系統。非常好! –

5

自動字符串連接只能用字符串文字作品

("{}".format("foo") 
"bar") 

這類似於你是什麼這樣做。解析器看到類似這樣的內容:

"{}".format("foo") "bar" 

(因爲它會連接有未終止括號的行),這顯然是無效的語法。要修復它,你需要明確地連接字符串。例如:

("{}".format("foo") + 
"bar") 

或者在整個字符串上使用字符串格式,而不是一次一個地使用字符串格式。