Technical skill practice
strip in Python: Trim End Characters without Removing a Prefix
Python str.strip removes matching characters from both ends of a string and returns a new string. With no argument it trims whitespace. Its chars argument describes individual removable characters, not a prefix token. Use removeprefix or removesuffix for a specific known token.
Start with a small, explicit task
Normalize a fictional imported label with spaces and marker characters. Then compare strip("AB-") with removeprefix("AB-") on a code whose legitimate body also contains A and B at its edges. The task is to preserve the body rather than deleting every matching end character.
Run the complete example
This original example was checked with Python 3.12.14. Save it as python_strip.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.
Expected output
Shelf 4
Z
BAZA
raw = " ##Shelf 4## "
cleaned = raw.strip().strip("#")
code = "AB-BAZA"
stripped = code.strip("AB-")
prefix_removed = code.removeprefix("AB-")
assert cleaned == "Shelf 4"
assert raw == " ##Shelf 4## "
assert stripped == "Z"
assert prefix_removed == "BAZA"
assert "left-middle-right".strip("-") == "left-middle-right"
print(cleaned)
print(stripped)
print(prefix_removed)
Explain the result
The first trim removes outer whitespace; the second removes hash characters now exposed at the ends. The original raw string is unchanged, so the returned value must be retained. strip does not search through the middle of a string to remove every occurrence of a character.
The code example exposes the token mistake. strip("AB-") can remove A, B and hyphen in any sequence from either edge, leaving only Z. removeprefix removes the single matching AB- token and leaves BAZA intact. These are both valid operations, but only one satisfies the stated prefix-normalization rule.
Avoid these mistakes
Do not chain broad trimming rules without deciding which meaningful characters they may delete. If only the right end should be cleaned, choose rstrip with an explicit rule; if a known suffix should disappear, use removesuffix. removeprefix is available in Python 3.9 and later, including the checked 3.12 runtime.
Questions, answered
Why did strip remove more than my prefix?
Its chars argument is a collection of characters to trim repeatedly at the ends, not a single token.
Does strip change the original string?
No. The raw-value assertion shows that you need to use the returned string.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.