String Methods and Manipulation
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…
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().
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.
True
FalseThe 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.
Finding a Course Label
Use find() to locate TEC inside the string IJK TEC.
- 1Start with the string
The text is IJK TEC.
- 2Search for the substring
The expression
label.find("TEC")asks the string to locate TEC. - 3Read the position
TEC begins after the three characters IJK and the space, so its numeric starting position is 4.
label.find("TEC") returns 4.
4Joining 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.
String, Methods, PythonNotice 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.
label = "IJK TEC"
label.find("TEC")
print(label)The search result is not stored, so label remains the original string.
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.
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.
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)- 1The first method checks whether course begins with IJK.
- 2The second method locates TEC inside course.
- 3The third method combines the strings in parts into one string.
- 4The 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.
True
4
String | Methods | PythonMistakes Beginners Make
Common mistake Treating startswith() as a general search
What it looks likecourse.startswith("TEC") when TEC appears later in the string
Why it failsstartswith()checks the beginning of the string, not an arbitrary location.Do this insteadUse 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 likeposition = course.find("TEC")Why it failsfind()locates the substring and returns its numeric starting position.Do this insteadUse the returned number as the position of the found text.
Common mistake Calling join() on the sequence instead of the delimiter
What it looks likeparts.join(", ")Why it failsThe delimiter is the string that calls
join(); the sequence is supplied to it.Do this insteadWrite ", ".join(parts).Common mistake Assuming a string method changes the original string
What it looks likelabel.find("TEC") followed by expecting label itself to become a position
Why it failsString methods return new values and do not modify the original string because strings are immutable.
Do this insteadAssign the returned value when you need to keep it.
Practice Tasks
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.
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
- 1Strings are objects belonging to the str class, so they provide methods for working with text.
- 2
startswith()checks whether a string begins with a specified prefix. - 3
find()locates a substring and returns its numeric starting position. - 4
join()combines a sequence of strings using a delimiter. - 5String methods return new values rather than modifying the original string because strings are immutable.
- 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, andjoin()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.