Concepts / String Methods and Manipulation

String Methods and Manipulation

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…

Strings as Objects

A Python string is more than a sequence of visible characters. It is an object belonging to the str class. Because it is a str object, it has methods for checking, searching, and transforming text. A method is an operation that you call through the string object, such as startswith(), find(), or join().

"Python"string objectstrclassstartswith()checks a prefixfind()locates textjoin()combines stringsbelongs toprovidesprovidesprovides
How is a string object connected to the str class and the methods available on it?

Checking a Prefix

The startswith() method checks whether a string begins with particular characters. It compares the beginning of the string with the prefix you provide and returns a result indicating whether the prefix matches.

python
Output
True
False

The first check succeeds because IJK is at the beginning of the string. The second check fails because TEC appears later, not at the beginning. startswith() is useful when a program needs to check a label, command, identifier, or other piece of text before deciding what to do next.

Locating Text with find

The find() method searches a string for a substring and returns the substring's numeric starting position in the original string. This lets you move from a text-search question to a position that a program can use.

IJK TECoriginal stringIJKpositions 0–24starting positionspaceposition 3TECpositions 4–6containscontainsfind("TEC")returns
How does Python map the text found by find() to its numeric starting index in the original string?
Worked example

Finding a Course Label

Use find() to locate TEC inside the string IJK TEC.

  1. 1
    Start with the string

    The text is IJK TEC.

  2. 2
    Search for the substring

    The expression label.find("TEC") asks the string to locate TEC.

  3. 3
    Read the position

    TEC begins after the three characters IJK and the space, so its numeric starting position is 4.

Result

label.find("TEC") returns 4.

python
Output
4

Joining a Sequence

The join() method combines a sequence of strings into one string by placing a delimiter between the items. The delimiter is the string on which you call join(). For example, a comma-and-space delimiter can combine several words into a readable list.

Stringfirst item", "delimiterString, Methods,Pythoncombined stringMethodssecond itemPythonthird itembetween itemsbetween itemsfinal itemjoins
How does a separator move between the items in a sequence to produce one combined string?
python
Output
String, Methods, Python

Notice that join() is called on the delimiter, not on the sequence variable. The delimiter determines what appears between the items, while the sequence supplies the strings that are combined.

Method Results and Immutability

String methods return new values rather than modifying the original string. This is because strings are immutable. A method can inspect or transform text, but the original string remains unchanged unless you store the returned value in a variable or use it in another expression.

Before
label = "IJK TEC"
label.find("TEC")
print(label)

The search result is not stored, so label remains the original string.

After
label = "IJK TEC"
position = label.find("TEC")
print(label)
print(position)

label is still IJK TEC, and position stores the new result 4.

Discovering the str Toolkit

The three methods in this article are only part of the str class. Python's built-in help() function can show the available methods and their documentation. Use help(str) when you know that you need a string operation but do not yet know the method name.

python

Read the help output as documentation for the str class. It organizes the operations available to string objects, including methods for checking, searching, and transforming text. This makes help(str) a practical exploration tool rather than a method that changes a string.

A Method Pipeline

Practical string manipulation often combines several method results. A useful way to reason about such a task is to trace the operations in order: first inspect the text, then locate or produce a value, and finally use that value in the next step. Each method returns a value that can be assigned or used by later code.

Code walkthrough
course = "IJK TEC Academy"
is_course = course.startswith("IJK")
position = course.find("TEC")
parts = ["String", "Methods", "Python"]
topic_line = " | ".join(parts)
print(is_course)
print(position)
print(topic_line)
  1. 1
    The first method checks whether course begins with IJK.
  2. 2
    The second method locates TEC inside course.
  3. 3
    The third method combines the strings in parts into one string.
  4. 4
    The original course string is not modified by these method calls.
  • course stores the original string.
  • startswith() checks its beginning and produces a result.
  • find() searches the original string and produces a numeric starting position.
  • join() combines the items in parts using the delimiter |.
  • The three results are printed in the order in which they were created.
Output
True
4
String | Methods | Python
IJK TEC Academycoursestartswith("IJK")Truejoin(" | ")combined textfind("TEC")4String, Methods,Pythonsequenceinspectsearchcombine
What order do the string methods execute in, and how does each operation produce a value for the next part of the task?

Mistakes Beginners Make

  • Common mistake

    Treating startswith() as a general search

    What it looks like

    course.startswith("TEC") when TEC appears later in the string

    Why it fails

    startswith() checks the beginning of the string, not an arbitrary location.

    Do this instead

    Use startswith() for a prefix check and find() when you need to locate a substring.

  • Common mistake

    Expecting find() to return the matching text

    What it looks like
    position = course.find("TEC")
    Why it fails

    find() locates the substring and returns its numeric starting position.

    Do this instead

    Use the returned number as the position of the found text.

  • Common mistake

    Calling join() on the sequence instead of the delimiter

    What it looks like
    parts.join(", ")
    Why it fails

    The delimiter is the string that calls join(); the sequence is supplied to it.

    Do this instead
    Write ", ".join(parts).
  • Common mistake

    Assuming a string method changes the original string

    What it looks like

    label.find("TEC") followed by expecting label itself to become a position

    Why it fails

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

    Do this instead

    Assign the returned value when you need to keep it.

Practice Tasks

EASY

Create a string containing a course name. Use startswith() to check its opening text, use find() to locate one word inside it, and use join() to combine three related topic names with a delimiter. Store each returned value and describe what each result represents.

Hints
  • Call startswith() on the course string.
  • Call find() with a substring that appears inside the course string.
  • Call join() on the delimiter and pass it a sequence of strings.
MEDIUM

Use help(str) to explore the complete set of methods available for string objects. Choose one method you have not used before and explain whether it checks, searches, or transforms text based on its documentation.

Hints
  • Run help(str) in a Python environment.
  • Look through the documented methods associated with the str class.
  • Connect the method's purpose to checking, searching, or transforming text.

Key Takeaways

  1. 1
    Strings are objects belonging to the str class, so they provide methods for working with text.
  2. 2
    startswith() checks whether a string begins with a specified prefix.
  3. 3
    find() locates a substring and returns its numeric starting position.
  4. 4
    join() combines a sequence of strings using a delimiter.
  5. 5
    String methods return new values rather than modifying the original string because strings are immutable.
  6. 6
    help(str) provides documentation for exploring the wider set of string methods.

At a glance

  • A Python string is an object belonging to the str class.
  • Use startswith() for prefix checks, find() for locating text, and join() for combining strings with a delimiter.
  • String methods return values and do not modify the original string.
  • Use help(str) to discover and study additional string methods.

Related concepts

More concepts starting with S