2015-03-02 104 views
-2

爲了簡化我的一些代碼,我決定將查詢和HTML代碼移動到txt文件中。然而,問題出現了:我通常保存在代碼中的大部分查詢和HTML在中間都有變量。例如,我有這個在我的代碼:讀取txt文件並在文本中添加一個變量 - Python

count = 0 
for x in reviewers: 
    query = """select * 
from mytable 
where reviewer = """ + reviewers[count] 
    cur.execute(query) 
    count = count + 1 
    #do more stuff 

的問題是,我該如何保存txt文件查詢或HTML代碼,然後添加變量在字符串的中間?

謝謝!

回答

1

好了,所以這裏是我想出瞭解決方案與我希望它可以幫助 因此,您可以保存在文本文件中的查詢形式

SELECT * from %s where id = %d 

一旦你得到查詢,你可以把你的變量放在裏面。我假設我已經從文件中獲得查詢。

query = "SELECT * from %s where id = %d" 
completeQuery=query% ('myTable', 21) 
print completeQuery 

輸出將是

SELECT * from myTable where id = 21 

Reference

0

我還是不知道你想要什麼,下面就來讀取文件,並在文本中添加變量名

query = "" 
f = open("query_file",'r')  
query = f.read() # read the query file into a string 
f.close() 



for x in reviewers: 
    query = query+reviewers[count] # add variable name in the string assuming reviewers[count] gives a string 
    cur.execute(query) 
    count = count + 1 
    #do more stuff 

編輯

重要的一點字符串在Python是一種方式一成不變

如果要修改字符串,那麼你就必須創建一個新的字符串

爲如

query = "Select from Table" 

你想讓它Select Col from Table

這裏是你做什麼: -

add_me = "Col" 

new_string = query[:-10] + add_me + query[6:] 

現在new_string字符串將有Select Col from Table

+0

你說得對,我不太清楚,你的榜樣是有道理的,我的意思是,如果變量在發生什麼中間的字符串,最後不對 – rodrigocf 2015-03-03 01:40:06