跳到内容

slice-to-remove-prefix-or-suffix (FURB188)

派生自 refurb 代码检查工具。

修复总是可用的。

作用

检查可以使用 str.removeprefix()str.removesuffix() 更简洁地编写的代码。

具体来说,该规则标记了以下代码:条件性地使用切片操作删除前缀或后缀,该切片操作紧跟在使用了 str.startswith()str.endswith()if 测试之后。

仅当您的项目目标为 Python 3.9 或更高版本时,才会应用此规则。

为什么这不好?

Python 3.9 中引入的 str.removeprefix()str.removesuffix() 方法具有相同的行为,同时更具可读性和效率。

示例

def example(filename: str, text: str):
    filename = filename[:-4] if filename.endswith(".txt") else filename

    if text.startswith("pre"):
        text = text[3:]

建议改为

def example(filename: str, text: str):
    filename = filename.removesuffix(".txt")
    text = text.removeprefix("pre")