String Basics and Indexing
When you see a string method such as startswith(), find(), or join(), you are using behavior provided by the str class.
Try it: Indexing and Slicing
How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.
How it works
- Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
- An index outside the string raises IndexError.
- A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
- A negative step walks backwards; a step of 0 is a ValueError.
Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).
Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.
Loading the simulation…
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 Is More Than Text
A string is a sequence of text, but in Python it is also an object belonging to the str class. Because it is an object, a string has methods: operations that can check, search, or transform text. This means that working with a string involves both the characters it contains and the operations available through str.
When you see a string method such as startswith(), find(), or join(), you are using behavior provided by the str class.
Character Positions
Indexing lets you refer to characters by position. Positive indices count from the beginning of the string, starting at zero. Negative indices count from the end, with the final character at position negative one. Indexing is useful when a task concerns a particular character rather than the entire string.
Finding a Character by Position
Use the string Python to identify its first character and its final character.
- 1First character
The first character is reached with positive index 0.
- 2Final character
The final character is reached with negative index -1.
- 3Check both directions
Positive indexing starts at the beginning, while negative indexing starts at the end.
For Python, index 0 identifies P and index -1 identifies n.
Three Useful String Methods
String methods let you express common text-manipulation tasks directly. startswith() checks whether a string begins with specified characters. find() locates a substring within a string. join() combines a sequence of strings using a delimiter. These methods illustrate three different kinds of work: checking, searching, and combining.
Choosing the Right Method
Select a string method for each task: check whether a title begins with a prefix, locate a word inside a sentence, or combine several words with a separator.
- 1Check a beginning
Use
startswith()when the question is whether text begins with particular characters. - 2Locate text
Use
find()when the task is to locate a substring. - 3Combine values
Use
join()when a sequence of strings must be combined with a delimiter.
The method should match the operation: startswith() checks, find() searches, and join() combines.
Why the Original Stays the Same
String methods return new values rather than modifying the original string. This behavior follows from string immutability: once a string exists, a method does not change that original string's contents. When a method appears to transform text, think of the result as a new value that can be used separately.
Discovering More with help(str)
The three methods in this lesson are only part of the behavior available for str objects. Python's built-in help() function can display the documentation for the str class. Running help(str) reveals the available methods and explains what each method does, which arguments it accepts, and what it returns.
- 1Identify the text task you need to solve.
- 2Use
help(str)to inspect the methods available for string objects. - 3Read the method descriptions, including accepted arguments and returned values.
- 4Choose a method whose documented behavior matches the task.
- 5Use the returned value while remembering that the original string remains unchanged.
Documentation is part of the programming process. You do not need to memorize every string method when help(str) can show the complete range and explain how each method behaves.
Mistakes with String Operations
Common mistake Treating startswith() as a general substring search
What it looks likeUsing startswith() when the needed text may appear anywhere in the string
Why it failsstartswith()tests the beginning of a string; it is not the method described for locating a substring.Do this insteadUse startswith() for a prefix check and find() when the task is to locate a substring.
Common mistake Assuming find() combines several strings
What it looks likeChoosing find() when the task is to assemble words with a delimiter
Why it failsfind()locates a substring, whilejoin()combines a sequence of strings.Do this insteadChoose join() for combining strings with a delimiter.
Common mistake Expecting a string method to modify the original string
What it looks likeAssuming that the original text has changed after a method call
Why it failsString methods return new values because strings are immutable.
Do this insteadWork with the returned value and treat the original string as unchanged.
Common mistake Guessing a method instead of checking its documentation
What it looks likeTrying to remember an unfamiliar string operation without consulting help(str)
Why it failsThe str class contains many methods, and their documentation explains their behavior, arguments, and return values.
Do this insteadUse help(str) to discover suitable methods and verify how they work.
Try the Method Match
For each task, choose between startswith(), find(), and join(): determine whether a product code begins with a given prefix; locate a particular word in a sentence; combine a list of words with a chosen delimiter.
Hints
- Ask whether the task checks a beginning, searches for a location, or combines values.
- Remember that
join()uses a delimiter to combine a sequence of strings. - If you cannot remember another string method, consult
help(str).
What do you think happens?
A string method appears to produce transformed text. Does that operation modify the original string or return a new value?
Reveal answer
It returns a new value and leaves the original unchanged.
Strings are immutable, so string methods do not modify the original string.
Key Takeaways
- Strings are objects belonging to the str class and provide methods for checking, searching, and transforming text.
- Positive string indices count from the beginning, while negative indices count from the end.
startswith()checks a prefix,find()locates a substring, andjoin()combines strings with a delimiter.- String methods return new values because strings are immutable; they do not modify the original string.
- Use
help(str)to discover available string methods and read their arguments, behavior, and return values.