2011-08-18 97 views
0

昨晚我在Boston Python Meetup上描述了各種Python實現。部分討論包括字符串連接。正確的CPython字符串連接

顯然,對於CPython,如果字符串以空字符串開始,然後使用連接進行連接,則會出現較少的堆碎片。

這是一個不錯的方式來構造字符串

sql_statement = "select count(*) " + \ 
    "from ept_inv e " + \ 
    "where e.ept_type = " + str(in_row[cs.DeviceType]) + " " + \ 
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; " 

或者我應該已經設置sql_statement""再加入每一塊? 謝謝。

+5

不管怎樣,你不應該直接在SQL語句中加入參數。 *始終*使用佔位符並將值作爲'參數'參數傳遞給'cursor.execute'。 –

回答

0

@robert有一個使用format()作爲字符串的非常好的觀點。 連接字符串的另一種方法是:

s = ('select count(*)' 
    'from ept_inv e' 
    'where e.ept_type = {device_type}' 
    'and e.inv_id = {endpoint_id};') 

sql_statement = sql_statement_format.format(
        device_type=in_row[cs.DeviceType], 
        endpoint_id=in_row[cs.EndpointId]) 

事實上,在Python,使用括號像這樣經由\優選截斷線。

2

請查看Python performance tips以獲取關於字符串連接的建議。

避免:

out = "<html>" + head + prologue + query + tail + "</html>" 

相反,使用

out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail) 
1

這應該是更快,更容易閱讀海事組織。這是相當少量的字符串連接,所以我不會把注意力集中在它上面:)。

" ".join([ 
    "select count(*)", 
    "from ept_inv e", 
    "where e.ept_type =", 
    str(in_row[cs.DeviceType]), 
    "and e.inv_id =", 
    str(in_row[cs.EndpointID]), 
    ";" 
]) 
+1

在這種情況下沒有像這樣連接字符串的要點。 –

3

你可以使用一個多行字符串字面與.format

sql_statement_format = """ 
    select count(*) 
    from ept_inv e 
    where e.ept_type = {device_type} 
    and e.inv_id = {endpoint_id}; 
""" 
sql_statement = sql_statement_format.format(
    device_type=in_row[cs.DeviceType], 
    endpoint_id=in_row[cs.EndpointId]) 

您需要正確地淨化你的SQL查詢,或bad things can happen。有什麼理由不使用Python數據庫API嗎?

+0

我發現mysqldb並開始使用它。 – octopusgrabbus

0

我懷疑這是過早的優化。只需以最易讀/ pythonic的方式進行操作,並且只有在使用真實世界的用例進行分析才能揭示字符串連接成爲熱點時才進行優化。

另外,請注意the comment。 :-)