Common String
Methods in Python
Master the essential string methods: split, join, strip, replace, and find to manipulate text data like a pro.
What Are String Methods?
In Python, strings are objects, and objects come with built-in functions called methods. You call a method using dot notation: write the string (or variable), then a dot, then the method name with parentheses.
The Five Core Methods
Why Do These Matter?
Almost every program deals with text: user input, file data, web content, messages. String methods let you clean, search, transform, and restructure that text efficiently.
split(): String → List
join(): List → String
strip(): Clean the Edges
replace(): Swap Substrings
The method replace(old, new) swaps every occurrence of old with new. To limit replacements, pass a third argument:
find(): Locate a Substring
split() vs join(): Inverses
find() vs replace()
| find() | replace() | |
|---|---|---|
| Purpose | Locate a substring | Swap a substring |
| Returns | An integer (index or -1) | A new string |
| Modifies? | No (read-only search) | No (returns new string) |
| Arguments | find(sub, start, end) | replace(old, new, count) |
| If not found | Returns -1 | Returns original string |
How to Apply String Methods
Example 1: Cleaning User Input
A user types their email with extra spaces. Clean it up using strip() and replace().
Example 2: Parsing CSV Data
Given a line from a CSV file, extract each field and rebuild it with a different separator.
Example 3: Search and Validate
Check if a URL contains "https" and find the position of the domain name.
Common Mistakes
Method Summary
| Method | Syntax | Returns |
|---|---|---|
| split() | str.split(sep) | list of strings |
| join() | sep.join(list) | a single string |
| strip() | str.strip(chars) | trimmed string |
| replace() | str.replace(old, new) | modified string |
| find() | str.find(sub) | int (index or -1) |
Question 1 of 5
What does "hello world".split() return?
Question 2 of 5
Which line correctly joins the list ["a", "b", "c"] into "a-b-c"?
Question 3 of 5
What is the output of this code?
print(" hi ".strip())
Question 4 of 5
What does "banana".find("na") return?
Question 5 of 5
After running this code, what is the value of x?