Concepts / Strings and String Methods

Strings and String Methods

Strings are objects belonging to the str class and possess methods for checking, searching, and transforming text.

  • 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…

Text with Built-In Behavior

A string is more than a sequence of visible characters. In Python, a string is an object belonging to the str class. Because it belongs to that class, it possesses methods for checking, searching, and transforming text. This lets you ask questions about text and create new text using operations attached to the string object itself.

Key point

The three methods in this lesson provide three different actions: startswith() checks a prefix, find() searches for a substring, and join() combines strings using a delimiter.

A String and Its Methods

When you work with a string, its methods are operations provided by the str class. The method call begins with a string value, followed by a dot and the method name. For example, a string can be used to call startswith(), find(), or join(). These methods return values. They do not modify the original string because strings are immutable.

A string valuetextstrclassstartswith()check a prefixfind()locate a substringjoin()combine stringsbelongs toprovidesprovidesprovides
How is a string value connected to the str class and to methods for checking, searching, and combining text?

Checking Prefixes with startswith()

The startswith() method tests whether a string begins with specified characters. Its result is a Boolean value: True when the beginning matches the prefix and False when it does not. This makes the method useful when a task depends on how text begins.

python
Output
True
False

In this example, the first call asks whether filename begins with report, so it produces True. The second call checks for data at the beginning, so it produces False. The method checks the prefix rather than searching for the text anywhere in the string.

Finding a Substring Position

The find() method searches for a substring inside a string and returns the character position where that substring begins. The returned position refers to the original string, so you can use it to understand where the match starts.

P0thonstarts at 22returned positiony1t2h3o4n5begins atfind() returns
How does find() connect a searched substring to its starting character position in the original string?
Worked example

Locating a Word

Find the starting position of the substring "thon" in the string "Python".

  1. 1
    Search

    Use find() on the string "Python" with "thon" as the substring being searched for.

  2. 2
    Map the match

    The substring begins after the first two characters, so its starting position is 2.

  3. 3
    Read the result

    The method returns the starting character position rather than the matched text itself.

Result

The starting position is 2.

python
Output
2

Combining Text with join()

The join() method combines a sequence of strings into one string. The string on which you call join() becomes the delimiter placed between the sequence elements. This means the method is organized around the separator: choose the separator first, then use it to join the strings.

", "separatorAda, Lovelaceone stringAda | Lovelacesequence of stringsplaced between itemsjoined
How does a separator and a sequence of strings become one combined string?
python
Output
Ada, Lovelace

Here, ", " is the delimiter and parts is the sequence being combined. The result is a new string containing the sequence elements with the delimiter between them.

Exploring the str Class

The three methods in this lesson are only part of the behavior available on str objects. Use the built-in help() function with str to explore the full range of string methods and read their documentation.

python

When you run help(str), Python exposes documentation for the str class, including the methods available for working with strings. Treat it as a reference to consult when you need a string operation that is not covered by the methods you already know.

Mistakes with String Methods

  • Common mistake

    Expecting startswith() to search anywhere in the string.

    What it looks like
    Using startswith() to check whether "archive_report.txt" contains "report".
    Why it fails

    startswith() tests the beginning of the string, not an arbitrary location within it.

    Do this instead

    Use find() when the task is to locate a substring and obtain its starting position.

  • Common mistake

    Expecting find() to return the matched substring.

    What it looks like

    Treating the result of find("thon") as the text "thon".

    Why it fails

    find() locates the substring and returns its character position.

    Do this instead

    Interpret the result as the starting position of the match.

  • Common mistake

    Expecting a string method to change the original string.

    What it looks like

    Calling a string method and then assuming the original string has been replaced.

    Why it fails

    String methods return new values, and strings are immutable.

    Do this instead

    Store or use the returned value when you need to keep the result.

  • Common mistake

    Choosing the wrong object as the join separator.

    What it looks like

    Trying to make a comma-separated result without calling join() on the comma separator.

    Why it fails

    The string on which join() is called becomes the delimiter between the sequence elements.

    Do this instead
    Call join() on the separator, such as ", ".join(parts).

Practice: Choose the Method

EASY

For each task, choose startswith(), find(), or join(). Then describe what kind of result the method should produce: a Boolean, a character position, or a new combined string.

Hints
  • A prefix check asks about the beginning of a string.
  • A search for a substring asks where text begins.
  • Combining several strings requires a delimiter and a sequence.
Worked example

Applying the Three Methods

Choose the appropriate method for these tasks: check whether "invoice_7" begins with "invoice", locate "7" in "invoice_7", and combine "invoice" and "7" with an underscore.

  1. 1
    Check the beginning

    Use startswith() because the task asks whether the string begins with a particular prefix.

  2. 2
    Locate text

    Use find() because the task asks for the position of a substring.

  3. 3
    Combine parts

    Use join() with an underscore as the delimiter because the task asks for one string made from multiple strings.

Result

The methods are startswith(), find(), and join(), respectively. Their results are a Boolean, a position, and a newly combined string.

What to Remember

  1. 1
    Strings are objects belonging to the str class.
  2. 2
    startswith() checks whether a string begins with a specified prefix and returns a Boolean result.
  3. 3
    find() searches for a substring and returns its starting character position.
  4. 4
    join() combines a sequence of strings using the string on which join() is called as the delimiter.
  5. 5
    String methods return new values rather than modifying the original string, and help(str) provides documentation for discovering more methods.

At a glance

  • A Python string is an object belonging to the str class.
  • Use startswith() for prefix checks, find() for substring positions, and join() for combining strings.
  • String methods return new values because strings are immutable.
  • Use help(str) to discover and read documentation for additional string methods.

Related concepts

More concepts starting with S