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

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

In this guide
  1. Nothing is modified in place
  2. split and join
  3. strip removes characters, not a suffix
  4. Tests that read as English
  5. Case methods and comparison
  6. Cleaning input, in order
  7. Searching without exceptions
  8. Splitting text into lines and fields
  9. Building strings in a loop
  10. replace, and the count nobody passes
  11. A worked example: cleaning one messy line
  12. Padding and aligning without counting spaces
  13. The is-something tests, and the one that lies
  14. Why strings are immutable at all
  15. Unicode, and what a character actually is
  16. When to stop using string methods
  17. Questions people ask about String Methods
  18. String Methods: recap in one screen

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.

Nothing is modified in place

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

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

name = name.upper()

This is the single most common string mistake. It fails silently. No error, just the old value sitting unchanged.

Understanding immutability is the first step to using string methods correctly. Every method call produces a new string object. The original string is never modified. That applies to every method on this page: upper, lower, strip, replace, split, join, and the rest. Each one returns a new string, and the caller is responsible for saving it.

Python has dozens of string methods. You do not need to memorize them all. A handful cover the vast majority of everyday text work. split breaks a string into a list of pieces. join does the opposite, gluing a list of strings together with a separator. strip removes whitespace from both ends. replace swaps one substring for another. startswith and endswith check prefixes and suffixes. find locates a substring and returns its position, or -1 if missing.

Method chaining is common. Because each method returns a new string, you can call the next method directly on the result. text.strip().lower().replace(" ", "_") cleans whitespace, lowercases, and replaces spaces in one expression. Each method sees the string produced by the previous one.

The in operator tests whether one string contains another. "ana" in "banana" is True. It is case-sensitive, so "Ana" in "banana" is False. If you need a case-insensitive check, convert both sides to the same case first: "ana" in "banana".lower().

Formatting is often grouped with string methods, but f-strings have mostly replaced the older .format() method. This page focuses on the methods that transform and inspect strings rather than format them.

This page covers immutability, split and join, strip and replace, searching with find and in, case methods, and the method-chaining pattern.

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. This Reads backwards until you've seen it a few times. Think of it as "put this between them".

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

split() with no arg is a different function . It splits on any run of whitespace and discards empties. This 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")

drops any leading or trailing a or b. It doesn't drop the string "ab". The arg 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 just because the strip misuse was so common.

Tests that read as English

startswith, endswith, isdigit, isalpha all return booleans and read on its own in a rule. endswith accepts a tuple. name.endswith((".jpg", ".png")) is one call rather than two checks.

Case methods and comparison

upper, lower and title return new strings. For case-insensitive check, lower() both sides. Or casefold(). This Handles a few non-English cases lower doesn't.

Cleaning input, in order

Text arriving from a person or a file often needs the same three steps, and the order is worth doing on purpose.

Strip first, because trailing whitespace and newlines break checks in ways that are invisible on screen. Norm case next, when the check should skip it. Only then split or compare.

line.strip().lower().split(",")

Chaining works because each method returns a new string. This Is the same immutability that makes losing to assign such a common mistake elsewhere.

For case-insensitive check across languages, casefold is stricter than lower and handles a handful of cases lower doesn't. For English-only text the difference never shows up.

Searching without exceptions

Three ways to ask whether a thing appears in a string, and they differ in what they give back:

"cat" in text            # True or False
text.find("cat")         # index, or -1
text.index("cat")        # index, or raises ValueError

Use in when you only want to know. Use find when you want the spot and lack is expected. Use index when lack is a bug and you want it to say so. Choosing find and then losing that -1 is falsy in a different way from 0 is a small classic: if text.find("cat"): is true when the match is at spot one and false when it's at spot zero.

Splitting text into lines and fields

splitlines() handles the newline variants that split("\n") gets wrong on files written on another operating system. split splits once and always returns three pieces, which avoids the length check that split with a maxsplit needs:

key, sep, value = line.partition("=")

If the separator was absent, sep is empty and value is empty, and the unpacking still works - no IndexError, no branch.

Building strings in a loop

Repeated concatenation inside a loop creates a new string each time, because strings can't be modified in place. For a handful of pieces that is irrelevant. For thousands it's truly slow, and the fix is to collect and join once:

parts = []
for row in rows:
    parts.append(format(row))
text = "\n".join(parts)

This is the same reason join exists as a method on the separator: it's building the whole result in one pass. This It can only do if it's given all the pieces at once.

replace, and the count nobody passes

replace swaps each hit and, like all else here, returns a new string:

text = "a-b-c-d"
print(text.replace("-", " "))
print(text.replace("-", " ", 2))
print(text)
a b c d
a b c-d
a-b-c-d

The third arg caps how many are replaced, counting from the left, and it is the one people forget exists. It saves a regular formula oddly often. The last line is the reminder that text itself never changed.

count answers the related question without doing the work: text.count("-") is 3 here, and returns 0 rather than raising when there are none.

A worked example: cleaning one messy line

Real text arrives with the wrong spacing, the wrong case, and a newline on the end. The methods on this page compose into a single readable pass:

raw = "  Ana , 91 ,  Physics\n"

name, score, subject = [f.strip() for f in raw.strip().split(",")]

print(repr(name), int(score), repr(subject))
'Ana' 91 'Physics'

Two strips are doing different jobs and both are needed. The outer raw.strip() drops the leading spaces and the trailing newline from the line as a whole. The one inside the comprehension drops the spaces around each field, which the outer one couldn't reach. Splitting first and stripping each piece is the general shape. Stripping only the whole line leaves " 91 ", which int() happens to forgive and a string check doesn't.

repr() in the output is there on purpose. Printing a string that still has a stray space looks the same to one that doesn't. repr is how you see the difference.

Padding and aligning without counting spaces

rows = [("ana", 91), ("bo", 7), ("caroline", 143)]
for name, n in rows:
    print(name.ljust(10, ".") + str(n).rjust(4))
ana.......  91
bo........   7
caroline.. 143

ljust, rjust and center take a width and an optional fill character. zfill is the special case for numbers: "7".zfill(3) gives "007", and it handles a leading minus sign right. This rjust(3, "0") doesn't.

The f-string spellings are f"{name:<10}", f"{n:>4}" and f"{n:^4}", and they're often the better choice because the value and its formatting stay together. The methods are worth knowing for when the width is found rather than literal.

The is-something tests, and the one that lies

print("42".isdigit(), "4.2".isdigit(), "-4".isdigit())
print("42".isdecimal(), "\u00b2".isdigit(), "\u00b2".isdecimal())
True False False
True True False

isdigit isn't "would int() accept this". It rejects a decimal point and a minus sign, and it accepts superscripts and other numeric characters that int() refuses. isdecimal is the stricter one and the closer match to what people often mean.

The solid test for "is this a number" is to try the conversion:

def is_int(text):
    try:
        int(text)
    except ValueError:
        return False
    return True

That handles the minus sign, the nearby whitespace and the underscores Python allows in numeric literals, all of which the is methods get wrong in one direction or the other. isalpha, isspace and isupper have no such problem and are safe to use right.

Why strings are immutable at all

Beginners meet immutability as an inconvenience — the reason name.upper() seems not to work. It's worth knowing what the language buys with it, because the same property shows action in a few other places.

A string that can't change can be shared without anyone worrying about who else holds it. Python takes edge of that constantly: the same short strings in your source are often the same object in memory, string constants can be stored once and pointed at from many places. Passing a string to a function costs nothing even so of its length, because nothing is copied.

It also makes strings hashable, and so usable as dict keys and set members. A hash is found from the contents. If the contents could change, the key would end up filed under a hash that no longer matches it, and lookups would silently fail. This is just why lists can't be keys and tuples can. each dict you index by name leans on strings being immutable.

The cost is real and narrow: building a string by repeated concatenation is quadratic, because each step copies all so far. That is the one place where the design bites, and join exists to cover it. all over else, the ensure that a string you were handed is the string you still have is worth a lot more than the ability to edit one in place.

Unicode, and what a character actually is

A Python string is a sequence of Unicode code points, not bytes. For English text the gap never comes up, and outside English it comes up right away.

len("café") is 4, which is what you'd hope. But the same text can be written two ways in Unicode. As an é code point, or as e followed by a mixing accent — and in the second form len reports 5 while the text looks the same on screen. unicodedata.norm("NFC", text) merges the second form into the first, and norming before checking is the fix for "these two strings look the same and aren't equal".

Emoji push this further: many are a few code points joined together, so slicing a string by index can cut one in half and give a thing that will not render. If you're truncating text that might hold them, count grapheme clusters with a library rather than characters.

Encoding is the separate question of how those code points become bytes for a file or a network. text.encode("utf-8") makes bytes; data.decode("utf-8") goes back. The errors people hit — UnicodeDecodeError on reading a file, mojibake like é where é should be — are almost always a file written in one encoding and read in another. UTF-8 is the right default all over, and giving it by name when opening files is worth the few extra characters, because the default still varies by platform.

When to stop using string methods

The methods on this page handle a great deal, and there's a point past which they stop being the right tool. The signal is a chain of split, strip, find and slicing that is getting longer each time the input surprises you.

If the pattern is truly variable — optional whitespace, options, repetition, groups you want to capture. That is what regular expressions are for, and re.search with a named group will be shorter and easier to fix than eight lines of index math. The trade is that a regular formula is harder to read for anyone who doesn't write them often. It earns its place only when the string methods have truly run out.

If the text is a known format, don't parse it by hand at all. JSON, CSV, INI files, dates, URLs and email handles all have a module in the standard library that has already handled the edge cases you haven't thought of yet: quoted commas inside a CSV field, escaped characters in JSON, timezone suffixes, percent-encoding. Hand-rolled parsing of a standard format is the most solid way to give a program that works on your test file and fails on real data.

The rule that follows is a simple one. String methods for cleaning and simple splitting, a parser for any of it with a specification, and regular expressions for the truly irregular middle ground.

Questions people ask about String Methods

Why does strip() not drop a suffix? Because its arg is a set of characters to drop from each end, not a string to match. Use removesuffix for the other job.

Is + on strings really slow? Not for a few pieces. It's slow inside a loop over thousands. Each + builds a whole new string. Collect into a list and join once.

What is the difference between find and index? find returns -1 when absent, index raises ValueError. Pick based on whether lack is expected or a bug.

How do I split on more than one separator? re.split from the re module — str.split takes one separator only.

Why does "".join(numbers) fail? join needs strings. Convert first: "".join(str(n) for n in numbers).

Does lower() work for each language? Mostly. casefold() is the more aggressive version intended for caseless check, and it's what to use when the text isn't ensured to be English.

How do I check a string against a few endings? endswith accepts a tuple: name.endswith((".jpg", ".png")).

String Methods: recap in one screen

  • each string method returns a new string. If you don't assign the result, nothing happened.
  • join is called on the separator and needs strings. split() with no arg is the forgiving version.
  • strip takes characters, not a suffix — removeprefix and removesuffix exist for that.
  • find returns -1, index raises. in is the one to use when you only need a yes or no.
  • isdigit isn't "is a number" — try the conversion instead.

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

Split, join, strip and test strings with Python's built-in methods, and see how each one returns a new string instead of changing the original.

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.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.