Removeprefix Removesuffix Trim Known Affixes

str.removeprefix and str.removesuffix strip a known affix and return the string untouched when it is absent, replacing fragile slicing.

PythonData Integrity

Code

pythonsnippet
17 lines
# 去已知前缀:不存在时原样返回,不会像切片那样悄悄裁错位置
order_id = "ORD-2026-0042"
print(order_id.removeprefix("ORD-"))
print(order_id.removeprefix("INV-"))

# removesuffix 处理尾部:文件扩展名与临时后缀场景
name = "report-draft.txt.bak"
print(name.removesuffix(".bak"))

# 与 startswith 组合写分支:先判断再摘掉,语义一目了然
tagged = "wip:fix-login"
if tagged.startswith("wip:"):
    print(tagged.removeprefix("wip:"))

# 边界:前缀恰好等于整串时得到空串,不匹配时保持原样
print("v2".removeprefix("v2"))
print("v2".removeprefix("v3"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

2026-0042
ORD-2026-0042
report-draft.txt
fix-login

v2

What the code does

Module-level bindings hold the data — order_id, name, tagged — with no function scope in between.

Using it

Running the file prints labeled results such as v2 — each operation’s effect is visible in the output.

Key statements

if tagged.startswith("wip:"):
    print(tagged.removeprefix("wip:"))

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `order_id`, `name`, `tagged`.