removeprefix And removesuffix Trim Affixes

Trim known prefixes and suffixes with removeprefix and removesuffix, which return the string untouched when the affix is absent instead of raising.

PythonConfig Management

Code

snippet
flag = "--dry-run"
command = flag.removeprefix("--")
print(command)

# 后缀同理:去掉单位尾巴
value = "150ms".removesuffix("ms")
print(int(value))

# 缺失时原样返回,不需要先判断 startswith
print("enabled".removeprefix("--"), "--disabled".removeprefix("--"))

# 链式清理配置键:环境变量前缀 + 类型后缀
def normalize_key(env_key):
    return env_key.removeprefix("APP_").removesuffix("_STR").lower()

for raw_key in ["APP_DATABASE_URL_STR", "APP_RETRIES", "OTHER_PORT"]:
    print(raw_key, "->", normalize_key(raw_key))

# 与切片手写的区别:手写版在缺失时会切错位置
name = "report.txt"
print(name[:-4] if name.endswith(".txt") else name, name.removesuffix(".txt"))

Output

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

dry-run
150
enabled disabled
APP_DATABASE_URL_STR -> database_url
APP_RETRIES -> retries
OTHER_PORT -> other_port
report report

How execution moves through the file

flag.removeprefix("--") strips the leading dashes from "--dry-run" unconditionally, and "150ms".removesuffix("ms") peels the unit off "150ms" so int(value) gets a pure number. The third print demonstrates the no-check contract on both sides: "enabled".removeprefix("--") is returned untouched, while "--disabled".removeprefix("--") loses the prefix — neither line needs a guard.

normalize_key chains both methods: env_key.removeprefix("APP_").removesuffix("_STR").lower() normalizes APP_DATABASE_URL_STR to database_url, while APP_RETRIES (no _STR) and OTHER_PORT (no APP_ prefix) pass through the chain unharmed. The last comparison shows why the methods exist: name[:-4] if name.endswith(".txt") else name needs an explicit conditional because slicing the wrong length corrupts the value, while name.removesuffix(".txt") is a single safe call.

Points of care

  • These methods match literal affixes — no glob, no regex; removesuffix("ms") on a value ending "seconds" removes nothing.
  • An empty affix (removeprefix("")) is a no-op that still returns a new string.

Using it

Entry signature: def normalize_key(env_key)

The run emits 1 labeled section — enabled — one per step.

Import normalize_key from the file and call it — the rest of the code is implementation detail.

Key statements

def normalize_key(env_key):
    return env_key.removeprefix("APP_").removesuffix("_STR").lower()

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `normalize_key` at load time.