octopusgrabbus octopusgrabbus - 2 months ago 12
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
sql_statement
to
""
and then joined each piece?
Thanks.

Answer

@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 \.

Comments