Strings and String Methods
Strings are objects belonging to the str class and possess methods for checking, searching, and transforming text.
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
- Each method call reads the string it is called on from left to right (strip also trims from the right end).
- 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.
- 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.
- 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.
- 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.
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.
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.
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.
True
FalseIn 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.
Locating a Word
Find the starting position of the substring "thon" in the string "Python".
- 1Search
Use
find()on the string "Python" with "thon" as the substring being searched for. - 2Map the match
The substring begins after the first two characters, so its starting position is 2.
- 3Read the result
The method returns the starting character position rather than the matched text itself.
The starting position is 2.
2Combining 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.
Ada, LovelaceHere, ", " 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.
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 likeUsing startswith() to check whether "archive_report.txt" contains "report".Why it failsstartswith()tests the beginning of the string, not an arbitrary location within it.Do this insteadUse 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 likeTreating the result of find("thon") as the text "thon".
Why it failsfind()locates the substring and returns its character position.Do this insteadInterpret the result as the starting position of the match.
Common mistake Expecting a string method to change the original string.
What it looks likeCalling a string method and then assuming the original string has been replaced.
Why it failsString methods return new values, and strings are immutable.
Do this insteadStore 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 likeTrying to make a comma-separated result without calling join() on the comma separator.
Why it failsThe string on which
join()is called becomes the delimiter between the sequence elements.Do this insteadCall join() on the separator, such as ", ".join(parts).
Practice: Choose the Method
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.
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.
- 1Check the beginning
Use
startswith()because the task asks whether the string begins with a particular prefix. - 2Locate text
Use
find()because the task asks for the position of a substring. - 3Combine parts
Use
join()with an underscore as the delimiter because the task asks for one string made from multiple strings.
The methods are startswith(), find(), and join(), respectively. Their results are a Boolean, a position, and a newly combined string.
What to Remember
- 1Strings are objects belonging to the str class.
- 2
startswith()checks whether a string begins with a specified prefix and returns a Boolean result. - 3
find()searches for a substring and returns its starting character position. - 4
join()combines a sequence of strings using the string on whichjoin()is called as the delimiter. - 5String 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, andjoin()for combining strings. - String methods return new values because strings are immutable.
- Use
help(str)to discover and read documentation for additional string methods.