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.
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…
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(...).
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.
| Method | Purpose | Kind of result |
|---|---|---|
| startswith() | Tests whether text begins with a prefix | A Boolean result |
| find() | Locates a substring | An index when found; -1 when absent |
| join() | Combines a sequence with a delimiter | A 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.
text = "Python strings"
found_position = text.find("strings")
missing_position = text.find("cloud")- 1The first search looks for text that is present.
- 2The second search looks for text that is not present.
- 3The 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.
7
-1Treat 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.
red, green, blueIn 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.
True
7
red, green, blueExploring 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.
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 likeposition = "Python strings".find("strings")Why it failsfind()locates a substring and returns its index, not the substring itself.Do this insteadUse the returned index as the position where the substring begins.
Common mistake Treating -1 as a valid match position
What it looks likeposition = "Python strings".find("cloud")Why it failsA result of -1 indicates that the substring is absent.
Do this insteadInterpret -1 as an unsuccessful search.
Common mistake Expecting a string method to modify the original string
What it looks likelabel = "Python strings" label.find("strings")Why it failsString methods return new values and do not modify the original string because strings are immutable.
Do this insteadStore 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 failsThe string before .join() supplies the delimiter, while the argument supplies the sequence of strings.
Do this insteadChoose the separator first, then pass the sequence to join().
Method Selection Practice
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().
Selecting the method
Match each task with startswith(), find(), or join().
- 1Prefix task
Use
startswith()because the task asks whether text begins with a specified prefix. - 2Search task
Use
find()because the task asks for the position of a substring. - 3Combination task
Use
join()because the task asks for one string made from a sequence and a delimiter.
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.