String Methods

split, join, strip, replace and the case methods - and the fact that none of them change the string they are called on.

Overview

Nothing is modified in place

name = "ana"
name.upper()      # result discarded
print(name)      # still "ana"

Strings are immutable, so a method that "changes" one actually returns a new one. If you do not keep the result, nothing happened. The fix is to rebind:

name = name.upper()

This is the single most common string mistake, and it fails silently — no error, just the old value.

string_methods.py

string_methods.py Python 3
Output

                    

split_join.py

split_join.py Python 3
Output

                    

Worth knowing

Strings are immutable: every method returns a new one and leaves the original alone.
split() with no argument splits on any run of whitespace; split(' ') does not.
join is called on the separator: ", ".join(parts).
strip("ab") removes any of those characters, not the string "ab". Use removesuffix for that.

String Methods: A Practical Guide

Python strings carry a large set of methods for splitting, joining, trimming and testing. All of them share one property that catches beginners: none of them change the string.

split and join

parts = "a,b,c".split(",")    # ['a', 'b', 'c']
",".join(parts)          # 'a,b,c'

join is called on the separator, not on the list, which reads backwards until you have seen it a few times. Think of it as "put this between them".

join requires strings. A list of numbers raises TypeError, so convert first: ",".join(str(n) for n in nums).

split() with no argument is a different function in practice: it splits on any run of whitespace and discards empties, which is what you want for scruffy text. split(" ") splits on each single space and will hand you empty strings between doubled spaces.

strip removes characters, not a suffix

"banana".strip("ab")

removes any leading or trailing a or b — it does not remove the string "ab". The argument is a set of characters. This trips people who write filename.strip(".csv") and find it also ate a trailing s or v.

For that job:

"report.csv".removesuffix(".csv")

removeprefix and removesuffix were added in Python 3.9 precisely because the strip misuse was so common.

Tests that read as English

startswith, endswith, isdigit, isalpha all return booleans and read naturally in a condition. endswith accepts a tuple, so name.endswith((".jpg", ".png")) is one call rather than two comparisons.

Case methods and comparison

upper, lower and title return new strings. For case-insensitive comparison, lower() both sides — or casefold(), which handles a few non-English cases lower does not.

Check yourself

0 of 3

Answer without scrolling back up.

  1. After `name = 'ana'` then `name.upper()`, what is name?

  2. What does `'banana'.strip('ab')` remove?

  3. `', '.join([1, 2])` does what?

Cheat sheet

String Methods

Python strings carry a large set of methods for splitting, joining, trimming and testing. All of them share one property that catches beginners: none of them change the string.

PYTHON · vizlearn.in/python/string_methods.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.