Concepts / Understanding Python Strings and String Methods

Understanding Python Strings and String Methods

The dot notation in a call such as text.find(...) expresses that the operation is being used through a string object.

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

A String Has Operations

A string is more than text stored in a variable. In Python, strings are objects belonging to the str class. Because they are str objects, they possess methods for checking, searching, and transforming text. This means that a string value can be followed by a dot and a method call, such as message.startswith(...) or message.find(...).

"Python"string valuestrclassstartswith()prefix checkfind()substring searchjoin()sequence combinationbelongs toprovidesprovidesprovides
How is a string value connected to the str class and the methods available on that object?
Key point

The dot notation in a call such as text.find(...) expresses that the operation is being used through a string object.

Three Useful Methods

Three practical string methods illustrate three different tasks. startswith() checks a prefix and produces a Boolean result. find() searches for a substring and produces its position when that substring is found. join() combines a sequence of strings by placing a delimiter between the items.

MethodPurposeKind of result
startswith()Tests whether text begins with a prefixA Boolean result
find()Locates a substringAn index when found; -1 when absent
join()Combines a sequence with a delimiterA combined string

The three string methods used in this lesson.

Finding Text by Index

find() searches a string for a specified substring. If the substring is present, the method returns the index at which that substring begins. If the substring is absent, find() returns -1. The returned value lets a program distinguish a successful search from an unsuccessful one.

P07found resulty1-1absent resultt2h3o4n56stringsstarts at index 7find("strings")find("cloud")
What index does find() return when a substring is found, and what value does it return when the substring is absent?
Code walkthrough
text = "Python strings"
found_position = text.find("strings")
missing_position = text.find("cloud")
  1. 1
    The first search looks for text that is present.
  2. 2
    The second search looks for text that is not present.
  3. 3
    The two returned values allow the program to tell these cases apart.
  • text contains the string being searched.
  • find("strings") returns the index where the matching substring begins.
  • find("cloud") returns -1 because that substring is absent.
Output
7
-1
Best practice

Treat the result of find() as information about the search. A nonnegative index identifies where the substring begins, while -1 indicates that the requested substring was not found.

Joining a Sequence

join() combines a sequence of strings into one string. The string on which join() is called acts as the delimiter, so the delimiter is placed between neighboring items in the sequence.

reditem", "delimiterred, green, bluecombined stringgreenitemblueitembetween itemsbetween itemsfinal itemcombine
How does a separator move between items in a sequence to produce one combined string?
python
Output
red, green, blue

In this example, the delimiter is ", ". It is placed between the three sequence items, producing one combined string. The original sequence is not described as being edited in place; join() returns a new string.

Inspecting and Returning Values

String methods can inspect text or return a newly formed value. startswith() and find() inspect the existing string: the first produces a prefix check and the second produces a search position. join() produces a combined string from a sequence. In every case, the method call gives you a result to use; it does not modify the original string.

Python stringsoriginal textTruestartswith result7find resultred, green, bluejoin resultstartswith("Python")find("strings")join(sequence)
What changes in the string after a method is applied, and which methods only inspect the string without changing its content?
python
Output
True
7
red, green, blue

Exploring str with help()

The three methods in this lesson are only part of the str class. Python's built-in help() function can display the available methods and their documentation. Calling help(str) is a practical way to explore the full range of operations before choosing a method for a string-manipulation task.

python

When the help display is long, search through it for a method whose purpose matches the task. For example, look for startswith() when the task is a prefix check, find() when the task is substring searching, and join() when the task is combining a sequence with a delimiter.

Mistakes with String Methods

  • Common mistake

    Assuming find() returns the matching text

    What it looks like
    position = "Python strings".find("strings")
    Why it fails

    find() locates a substring and returns its index, not the substring itself.

    Do this instead

    Use the returned index as the position where the substring begins.

  • Common mistake

    Treating -1 as a valid match position

    What it looks like
    position = "Python strings".find("cloud")
    Why it fails

    A result of -1 indicates that the substring is absent.

    Do this instead

    Interpret -1 as an unsuccessful search.

  • Common mistake

    Expecting a string method to modify the original string

    What it looks like
    label = "Python strings"
    label.find("strings")
    Why it fails

    String methods return new values and do not modify the original string because strings are immutable.

    Do this instead

    Store the returned value when the result is needed.

  • Common mistake

    Confusing the delimiter with the sequence being joined

    What it looks like
    ", ".join(["red", "green", "blue"])
    Why it fails

    The string before .join() supplies the delimiter, while the argument supplies the sequence of strings.

    Do this instead

    Choose the separator first, then pass the sequence to join().

Method Selection Practice

EASY

Choose the most suitable method for each task: checking whether "report.txt" begins with "report", locating "2026" inside a longer string, and combining ["IJK", "TEC", "Academy"] with a space delimiter.

Hints
  • A prefix check uses startswith().
  • A substring search uses find().
  • A delimiter combines a sequence through join().
Worked example

Selecting the method

Match each task with startswith(), find(), or join().

  1. 1
    Prefix task

    Use startswith() because the task asks whether text begins with a specified prefix.

  2. 2
    Search task

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

  3. 3
    Combination task

    Use join() because the task asks for one string made from a sequence and a delimiter.

Result

The method choices are startswith() for the prefix, find() for the substring position, and join() for combining the sequence.

Key Takeaways

  • Strings are objects belonging to the str class, so they provide methods for checking, searching, and transforming text.
  • startswith() checks whether a string begins with a specified prefix.
  • find() returns the starting index of a found substring and -1 when the substring is absent.
  • join() combines a sequence of strings by placing a delimiter between the items.
  • String methods return new values without modifying the original string, and help(str) displays available str methods and their documentation.

Related concepts

More concepts starting with U