01 / 20
.str methods

Common String
Methods in Python

Master the essential string methods: split, join, strip, replace, and find to manipulate text data like a pro.

Python

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.

name = " Hello, World! " clean = name.strip() print(clean) # "Hello, World!" print(name) # " Hello, World! " (unchanged)

The Five Core Methods

split()
Breaks a string into a list of substrings at a given delimiter
join()
Combines a list of strings into one string with a separator
strip()
Removes leading and trailing whitespace (or specified characters)
replace()
Swaps every occurrence of one substring for another
find()
Returns the index of the first occurrence, or -1 if not found

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.

1
Data cleaning: strip whitespace from user-submitted form fields
2
Parsing: split a CSV line into individual values
3
Search: find keywords inside a document or log file
4
Output formatting: join list items into a readable sentence

split(): String → List

"apple,banana,cherry" .split(",") "apple" "banana" "cherry" Result: ["apple", "banana", "cherry"]
fruits = "apple,banana,cherry" fruit_list = fruits.split(",") print(fruit_list) # ['apple', 'banana', 'cherry']

join(): List → String

"red" "green" "blue" " - ".join(...) "red - green - blue" The separator goes between each list item
colors = ["red", "green", "blue"] result = " - ".join(colors) print(result) # "red - green - blue"

strip(): Clean the Edges

" ··· Hello, World! ··· " ← spaces on both sides .strip() "Hello, World!" No more leading or trailing whitespace
raw = " Hello, World! " print(raw.strip()) # "Hello, World!" print(raw.lstrip()) # "Hello, World! " print(raw.rstrip()) # " Hello, World!"

replace(): Swap Substrings

msg = "I like cats and cats like me" new_msg = msg.replace("cats", "dogs") print(new_msg) # "I like dogs and dogs like me"

The method replace(old, new) swaps every occurrence of old with new. To limit replacements, pass a third argument:

msg.replace("cats", "dogs", 1) # "I like dogs and cats like me" # Only the first occurrence is replaced

find(): Locate a Substring

Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 H e l l o , W o r l d ! find("World") → 7 Returns the starting index of the match
text = "Hello, World!" print(text.find("World")) # 7 print(text.find("xyz")) # -1 (not found)

split() vs join(): Inverses

"a-b-c" String .split("-") "-".join(...) ["a","b","c"] List "a-b-c" String split() and join() are inverse operations separator.join(string.split(separator)) == original string

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

1
Identify the task: Are you cleaning, searching, splitting, joining, or replacing?
2
Choose the method: Match the task to the right method: strip for cleaning, split for parsing, etc.
3
Determine arguments: What delimiter, substring, or character do you need to pass?
4
Store the result: Assign the return value to a variable: strings are immutable, so the method won't change the original.
5
Chain if needed: You can chain methods: " Hi ".strip().lower().replace("hi", "hello")

Example 1: Cleaning User Input

A user types their email with extra spaces. Clean it up using strip() and replace().

raw_email = " User @Example.COM " # Step 1: Remove whitespace from edges trimmed = raw_email.strip() # "User @Example.COM" # Step 2: Remove internal spaces no_spaces = trimmed.replace(" ", "") # "User@Example.COM" # Step 3: Lowercase for consistency email = no_spaces.lower() # "user@example.com"

Example 2: Parsing CSV Data

Given a line from a CSV file, extract each field and rebuild it with a different separator.

csv_line = "Alice,25,Engineer,NYC" # Split into a list of fields fields = csv_line.split(",") # ['Alice', '25', 'Engineer', 'NYC'] # Access individual fields name = fields[0] # 'Alice' age = fields[1] # '25' # Rejoin with a different separator tab_line = "\t".join(fields) # "Alice\t25\tEngineer\tNYC"

Example 3: Search and Validate

Check if a URL contains "https" and find the position of the domain name.

url = "https://www.example.com/page" # Check for secure protocol pos = url.find("https") if pos == 0: print("Secure connection") # Find the domain start (after "://") start = url.find("://") + 3 # 7 end = url.find("/", start) # 22 domain = url[start:end] print(domain) # "www.example.com"

Common Mistakes

✕ Forgetting Immutability
Writing name.strip() without storing the result. The original variable is unchanged. Always assign: name = name.strip()
✕ Wrong join() Syntax
Writing my_list.join(",") instead of ",".join(my_list). The separator calls join, not the list.
✕ Using find() like a Boolean
Writing if text.find("x"): fails when the match is at index 0 (falsy). Use if text.find("x") != -1: or "x" in text

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?

s = "foo bar foo" x = s.replace("foo", "baz", 1)