CodeQL 文档

列表中的隐式字符串连接

ID: py/implicit-string-concatenation-in-list
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - maintainability
   - convention
   - external/cwe/cwe-665
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当两个字符串字面量并排放置时,Python 解释器会隐式地将它们连接成一个字符串。在某些情况下这很有用,但更常见的是造成误解或错误。

建议

如果连接是故意的,则使用 + 连接字符串。这没有运行时开销,并且可以明确表示意图。

示例

在下面的第一个函数 unclear 中,隐式字符串连接被使用了两次;一次是故意的,一次是意外的。在第二个函数 clarified 中,第一个连接被明确表示,第二个连接被删除。


def unclear():
    # Returns [ "first part of long string and the second part", "/usr/local/usr/bin" ]
    return [

        "first part of long string"
        " and the second part",
        "/usr/local"
        "/usr/bin"
    ]

def clarified():
    # Returns [ "first part of long string and the second part", "/usr/local", "/usr/bin" ]
    return [
        "first part of long string" +
        " and the second part",
        "/usr/local",
        "/usr/bin"
    ]

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私