brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: str.removeprefix instead of lstrip for a prefix

Scripting
~/tips/tip-python-str-removeprefix

>>> 'Arthur: three!'.lstrip('Arthur: ')

Removes an exact prefix from a string, unlike lstrip which strips a set of characters.

lstrip looks like it removes a prefix, but it removes characters, and the bug it causes is easy to miss.

lstrip('abc') removes any of the characters in its argument from the left, one by one, until it hits one that is not in the set. The docs show what that does to a prefix:

>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'

The first call ate the th and r of “three” too, because those letters are in the set. removeprefix, added in Python 3.9, removes the exact string once, and returns the original string when it does not start with it. A matching removesuffix exists:

name = "docker-compose.yml".removesuffix(".yml")
host = "https://example.com/a".removeprefix("https://")
# docker-compose
# example.com/a

The same trap exists for rstrip, which is why "report.html".rstrip(".html") is a bad way to drop an extension. Use removesuffix there.

Caveats: both methods only remove one copy, so "xxabc".removeprefix("x") gives "xabc", and both are case sensitive. If the input varies, lower-case it first, or compare with str.lower() before you decide what to remove. Before 3.9 you need s[len(p):] if s.startswith(p) else s.

Further reading: Built-in types: str.removeprefix

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil All Scripting tips (10) All topics

Link