Concepts / String Methods: replace() and split()

String Methods: replace() and split()

Method chaining combines multiple operations in one expression, but the order of the methods matters.

  • Programming
Interactive lab

Try it: String methods, character by character

How Python's str methods (split, strip, replace, find, count, startswith, join, in …) scan a string character by character — and that each call returns a new value while the original string never changes.

How it works

  1. Each method call reads the string it is called on from left to right (strip also trims from the right end).
  2. split() with no separator skips runs of whitespace and never returns empty strings; split(sep) cuts at every occurrence of sep and can return empty pieces; maxsplit limits the number of cuts.
  3. find, index, count, replace and `in` slide a window along the string; occurrences never overlap, find gives -1 and index raises ValueError when nothing matches.
  4. strip(chars) removes any of the given characters (a set, not a substring) from the ends until it meets one that is not in the set.
  5. Strings are immutable: every call returns a new str, list, int or bool, and the next call in the chain works on that new value.

Default run (62 steps): s = ' Apples, pears,,figs '. Evaluate ' | '.join(s.strip().lower().split(',')) one method call at a time, left to right. … ' | '.join(s.strip().lower().split(',')) → 'apples | pears | | figs'. And s is still ' Apples, pears,,figs '.

Simplified: Printable ASCII text up to 30 characters and up to four chained calls with short arguments. CPython searches with a faster algorithm (fastsearch) than the window-by-window scan shown, but the results are the same.

Educational simulation

Loading the simulation…

Reading Text as Transformations

Python string methods let you process text through focused operations. In this lesson, you will trace how find(), strip(), startswith(), lower(), replace(), and split() contribute to text processing. The important habit is to ask what operation happens first, what value it produces, and what the next method receives.

Key point

Method chaining combines multiple operations in one expression, but the order of the methods matters.

Locating Text with find()

The find() method is used to locate the position of a character or substring within a string. It is useful when the question is not simply whether text exists, but where that text occurs in the original string. Positions in a string are counted from the beginning, so the method's result identifies a location within the string.

bananaoriginal stringanasubstringpositionlocation in the stringsearches forlocates
How does find() connect a substring with its position in the original string?
Worked example

Locating a repeated pattern

Consider the string banana and use find() to locate the substring ana.

  1. 1
    Start with the original string

    The text being searched is banana.

  2. 2
    Provide the target

    The target substring is ana.

  3. 3
    Read the result

    find() reports the position where the substring is located in the original string.

Result

find() is the appropriate method when you need a substring's position rather than a Boolean beginning-with check.

Cleaning Boundaries with strip()

The strip() method removes whitespace from the beginning and the end of a string. It does not remove spaces inside the text. This makes strip() useful when unwanted whitespace surrounds a value but the spacing within the value should remain unchanged.

red appleleading and trailingwhitespacered appleinternal space remainsstrip()
Which whitespace does strip() remove, and which spacing remains?
Worked example

Separating boundary cleanup from text editing

Consider a string containing two spaces before red apple and two spaces after it.

  1. 1
    Inspect the boundaries

    The spaces before the first letter and after the final letter are boundary whitespace.

  2. 2
    Apply strip()

    strip() removes the leading and trailing whitespace.

  3. 3
    Inspect the middle

    The space between red and apple is interior whitespace, so it remains.

Result

strip() cleans the edges without removing internal spaces.

Moving Through a Method Chain

A method chain passes the result of one operation into the next operation. For example, a chain can strip boundary whitespace, convert the text with lower(), and then perform another string operation. The order is part of the meaning: changing the order can change the value that the later method receives.

Hello Worldinput stringstrip()remove boundary whitespaceHello Worldafter first operationlower()convert text to lowercasehello worldafter second operationreplace()perform a replacementfirstproducesnextproducesnext
In what order does text move through strip(), lower(), and replace()?
Worked example

Tracing a chain one operation at a time

Trace a chain that first applies strip(), then lower(), and then replace() to text with boundary whitespace and uppercase letters.

  1. 1
    First operation

    strip() removes whitespace at the beginning and end while preserving interior spaces.

  2. 2
    Second operation

    lower() changes the text to lowercase, creating a new value for the next operation.

  3. 3
    Third operation

    replace() receives the lowercase result, so its matching behavior is based on that result rather than the original text.

Result

To understand a chain, write down the intermediate value after every method and verify that each later method receives the value produced immediately before it.

Key point

The same methods can behave differently in a chain when their order changes. Clean the boundaries, change the case, and perform later matching operations in the order your task requires.

Replacing and Splitting Text

replace() and split() represent two different kinds of text transformation. replace() produces a new modified string by changing matching text. split() breaks one string into a list of substrings. When choosing between them, decide whether you need one modified string or separate pieces of text.

red-blueone stringred greenmodified stringred, bluesubstrings in a listreplace()split()
How does replace() differ from split() in the value it produces?
MethodTransformationResult to expect
replace()Changes matching textA new modified string
split()Breaks one string into substringsA list of substrings

Choose the method according to the shape of result you need.

Case and Prefix Checks

startswith() checks whether a string begins with a specified value and returns a Boolean result. The check is case-sensitive, so uppercase and lowercase letters must match. For a case-insensitive check, use lower() first and then apply startswith() to the lowercase result.

Pythonbegins with uppercase PPymatching caseTrueBoolean resultpythonbegins with lowercase pPydifferent caseFalseBoolean resultchecks beginningmatcheschecks beginningcase differs
Why can startswith() return different results when the letter case changes?

Mistakes Beginners Make

  • Common mistake

    Expecting strip() to remove spaces between words

    What it looks like

    Applying strip() to text with an interior space

    Why it fails

    strip() removes only leading and trailing whitespace, not interior spaces.

    Do this instead

    Use strip() for boundary cleanup and preserve the internal spacing unless another operation is required.

  • Common mistake

    Assuming startswith() ignores uppercase and lowercase differences

    What it looks like

    Checking a lowercase string with an uppercase prefix

    Why it fails

    startswith() is case-sensitive.

    Do this instead

    Use lower() first when the check should be case-insensitive.

  • Common mistake

    Reading a method chain as if all methods run at once

    What it looks like
    Treating strip().lower().replace() as an unordered collection of operations
    Why it fails

    Each method receives the result produced by the method before it, so order matters.

    Do this instead

    Trace the chain from left to right and record the intermediate value after each method.

  • Common mistake

    Choosing replace() when separate substrings are needed

    What it looks like

    Using replace() for a task that requires a list of pieces

    Why it fails

    replace() produces a modified string, while split() breaks one string into a list of substrings.

    Do this instead

    Choose split() when the required result is separate substrings.

Practice the Trace

MEDIUM

A string contains boundary whitespace, uppercase letters, and multiple words. Plan a method chain that removes the boundary whitespace, converts the text to lowercase, and then performs a later text transformation. Before evaluating it, write down the value after each method. Then decide whether replace() or split() is appropriate for the final result.

Hints
  • Start with strip() because boundary whitespace should be removed before later operations.
  • Use lower() before a case-insensitive matching operation.
  • Choose replace() for one modified string and split() for a list of substrings.
EASY

Explain why a startswith() check can produce a different Boolean result when only the capitalization of the string changes. Then describe how lower() changes the procedure.

Hints
  • startswith() compares the beginning of the string with the specified value.
  • The comparison is case-sensitive.
  • Applying lower() first supports a case-insensitive check when the comparison value is handled consistently.

Key Takeaways

  1. 1
    Use find() when you need the position of a character or substring within a string.
  2. 2
    Use strip() to remove leading and trailing whitespace; interior spaces remain.
  3. 3
    Use startswith() to test a prefix and receive a Boolean result.
  4. 4
    Use lower() before a prefix or text comparison when the intended check should ignore case.
  5. 5
    Use replace() for a modified string, split() for a list of substrings, and remember that chained method order matters.

At a glance

  • find() locates a character or substring within a string.
  • strip() removes only whitespace at the beginning and end.
  • startswith() is a case-sensitive prefix check that returns a Boolean result.
  • replace() creates a modified string, while split() creates a list of substrings.
  • Chained methods run in order, so trace each intermediate result.

More concepts starting with S