Python foundations

Python String Methods: strip, split, join, and find

Clean and compare Python strings with strip(), split(), join(), find(), replace(), and casefold(). See what each method returns.

Use text.strip() to trim whitespace, text.split() to break text into pieces, and separator.join(parts) to put pieces back together. Python strings are immutable. Save a method’s result in a variable when you want to keep the changed text.

raw = "  Room 12  "
label = raw.strip()
assert label == "Room 12"
assert raw == "  Room 12  "

Trimming whitespace at an input boundary is often useful, but its meaning depends on the field. Preserve indentation when it represents structure, and keep the original value when you need a record of what someone entered.

Split on whitespace or a specific separator

text.split() with no separator treats runs of whitespace as boundaries and leaves out surrounding empty fields. text.split(",") uses a literal comma and preserves empty fields between consecutive commas. Both behaviors matter when a missing slot carries meaning.

assert "  red   blue  ".split() == ["red", "blue"]
assert "red,,blue".split(",") == ["red", "", "blue"]
assert "".split() == []
assert "".split(",") == [""]

If the input is CSV, use the CSV parser. Quoted fields may contain commas, and split(",") cannot tell these apart from separators. Simple splitting is appropriate when the input contract forbids nested delimiters and quoting.

To cut text at the first separator, use split(separator, 1) or partition(separator). With partition("="), "title=draft=v2" becomes ("title", "=", "draft=v2"). If there is no equals sign, the middle and last values are empty. Check the middle value when the separator is required.

Join pieces with a defined separator

Call separator.join(parts) to put a separator between strings. For example, " / ".join(["North", "Lab"]) produces "North / Lab". It does not add a separator before the first item or after the last. Convert values explicitly if the input contains numbers; the join operation requires strings.

For a report assembled in stages, collecting strings and joining them gives the line separator a single obvious home. If you want a final newline as part of a text file contract, add it separately. An empty list joins to an empty string, so decide what an empty report should contain before applying that final-newline rule.

Remove an exact prefix with the prefix method

strip(chars) treats its argument as a set of characters to remove from both ends. It does not look for one complete phrase. Use removeprefix(prefix) or removesuffix(suffix) for literal boundary text in Python 3.9 and later. For example, "draft_article".removeprefix("draft_") produces "article". A nonmatching prefix leaves the value unchanged.

replace(old, new) changes occurrences throughout a string. If your format has a structural prefix, a replace call can also modify valid content further in. Use a targeted operation and test an input containing the same phrase both at the boundary and in the middle.

Choose normalization for the field

lower() is useful for lowercase display. casefold() is more aggressive and fits many case-insensitive comparisons. For example, "Straße".casefold() and "STRASSE".casefold() match. Case folding does not by itself make every visually identical Unicode sequence equal. Unicode normalization is a separate operation. If the rule affects identifiers, preserve the original and document whether aliases should collapse together.

Finally, remember that bytes and strings have different roles. Decode bytes with the agreed encoding when entering text operations. Encode text when writing a byte-oriented format. Avoid str(raw_bytes) as a substitute for decoding, since it yields a representation such as "b'hello'" rather than the intended text. A good text cleanup test includes an empty field, non-ASCII text, and whatever the format says should happen to outer whitespace.

Find a piece of text without confusing a match at zero

Use needle in text for a yes-or-no check. Use text.find(needle) to get the first matching index. Test position >= 0 to check the result. A match at the beginning returns zero, which is false in a condition. An absent match returns -1, which is true in a condition.

text = "draft: notes"
assert text.find("draft") == 0
assert text.find("final") == -1
assert "notes" in text

text.index(needle) performs a similar search but raises ValueError when the text is absent. Use it when the required substring should always be present. Use membership or find when absence is one of the expected cases. If you only need to check the beginning or end, startswith or endswith says precisely where to look.

Keep cleaned text separate from its source when decisions depend on it

To compare two contact labels, you might ignore case and surrounding spaces. That rule is useful when checking for duplicates, but replacing the display label with the normalized value can strip the spelling the person prefers. Keep a display label and derive a comparison key separately.

If the input has documented rules for punctuation, apply them deliberately. Replacing every hyphen could collapse two labels that the source system treats as different. When a proposed rule merges distinct raw strings, exercise at least one example that is meant to merge and one that is meant to remain distinct. That makes the policy reviewable by someone who never sees the source code.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org