Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.
Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.
Is this an OK way to construct a string
sql_statement = "select count(*) " + \
"from ept_inv e " + \
"where e.ept_type = " + str(in_row[cs.DeviceType]) + " " + \
"and e.inv_id = " + str(in开发者_Go百科_row[cs.EndpointID]) + " ; "
or should I have set sql_statement
to ""
and then joined each piece?
Thanks.
You could use a multi-line string literal with .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])
You need to properly sanitize your SQL queries, or bad things can happen. Is there any reason you're not using the Python database API?
Please take a look at the Python performance tips for advice on string concatenation.
Avoid:
out = "<html>" + head + prologue + query + tail + "</html>"
Instead, use
out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
This should be faster and easier to read imo. This is a fairly small amount of strings to concatenate, so I wouldn't concentrate to much on it :).
" ".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]),
";"
])
@robert has a very good point of using format()
for a string.
Another way of concatenating strings is:
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])
In fact, in Python, using parenthesis like this is preferred to truncating lines via \
.
I suspect this would be premature optimization. Just do it in the most readable/pythonic way and only optimize it if profiling with real world use cases reveals your string concatenation to be a hot spot.
Also, heed the comment. :-)
精彩评论