正确的CPython字符串连接

2024-05-08 03:09:37 发布

您现在位置:Python中文网/ 问答频道 /正文

昨晚我参加了一个Boston Python Meetup会议,会上描述了各种Python实现。讨论的一部分包括字符串连接。你知道吗

显然,对于CPython来说,如果字符串从空字符串开始连接,然后使用join,则堆碎片会更少。你知道吗

这是构造字符串的好方法吗

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设置为"",然后把每一块都连接起来? 谢谢。你知道吗


Tags: 字符串insql会议cscpythonbostonrow
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吗?你知道吗

请查看Python performance tips以获得有关字符串连接的建议。你知道吗

Avoid:

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

Instead, use

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

@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中,使用这样的括号比通过\截断行更可取。你知道吗

相关问题 更多 >