octopusgrabbus octopusgrabbus - 1 year ago 163
Python Question

Proper CPython String Concatenation

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_row[cs.EndpointID]) + " ; "

or should I have set
and then joined each piece?

Answer Source

@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(

In fact, in Python, using parenthesis like this is preferred to truncating lines via \.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download