- Master common string transformation methods
- Search and analyze strings effectively
- Split and join strings
- Clean and validate user input
String Methods
Imagine you're a text editor. You need to correct typos, change formatting, search for words, and organize content. Doing this character by character would be exhausting! Python gives you powerful string methods – pre-built tools that handle common text operations in a single command.
String methods are like having a Swiss Army knife for text. Need to convert to uppercase? One method. Remove extra spaces? One method. Split a sentence into words? One method. Let's explore this toolbox!
Method Syntax
String methods are called using dot notation:
Method Syntax
"hello".upper()
Method name (action to perform)
String (the data to act on)
Key Points:
• Methods RETURN a new string (original unchanged!)
• Methods are called WITH parentheses ()
• Some methods take arguments: replace("a", "b")
Case Transformation Methods
Change the capitalization of text:
text = "Hello World"
# Convert to uppercase
print(text.upper()) # "HELLO WORLD"
# Convert to lowercase
print(text.lower()) # "hello world"
# Capitalize first letter only
print(text.capitalize()) # "Hello world"
# Title case (each word capitalized)
print(text.title()) # "Hello World"
# Swap case (upper↔lower)
print(text.swapcase()) # "hELLO wORLD"
# Original is UNCHANGED!
print(text) # "Hello World"
Visual Guide
Case Methods
Original: "heLLo WoRLD"
.upper() → "HELLO WORLD" (all uppercase)
.lower() → "hello world" (all lowercase)
.capitalize()→ "Hello world" (first char upper, rest lower)
.title() → "Hello World" (each word capitalized)
.swapcase() → "HEllO wOrld" (flip each case)
Practical Use: Case-Insensitive Comparison
user_input = "YES"
expected = "yes"
# Direct comparison fails
if user_input == expected: # False!
print("Match")
# Compare in same case
if user_input.lower() == expected.lower(): # True!
print("Match")
Trimming Methods
Remove unwanted whitespace:
messy = " Hello World \n"
# Remove from both ends
print(messy.strip()) # "Hello World"
# Remove from left only
print(messy.lstrip()) # "Hello World \n"
# Remove from right only
print(messy.rstrip()) # " Hello World"
# Remove specific characters
dirty = "###Hello###"
print(dirty.strip("#")) # "Hello"
When to Use strip()
Common strip() Uses
USER INPUT: Users often add accidental spaces
name = input("Name: ").strip()
FILE READING: Lines often end with \n
line = file.readline().strip()
WEB DATA: HTML often has extra whitespace
text = scraped_text.strip()
DATA CLEANING: CSV fields may have padding
value = csv_field.strip()
Search Methods
Find and locate text within strings:
text = "Hello, World! Hello, Python!"
# Check if contains substring
print("World" in text) # True (using 'in' operator)
# Find position (returns -1 if not found)
print(text.find("World")) # 7
print(text.find("Java")) # -1
# Find position (raises error if not found)
print(text.index("World")) # 7
# text.index("Java") # ValueError!
# Count occurrences
print(text.count("Hello")) # 2
print(text.count("o")) # 4
# Check start/end
print(text.startswith("Hello")) # True
print(text.endswith("!")) # True
find() vs index()
find() vs index()
text = "Hello World"
find("World") → 6 (found at index 6)
find("Python") → -1 (not found, returns -1)
index("World") → 6 (found at index 6)
index("Python") → ERROR! (not found, raises ValueError)
Use find() when missing value is normal
Use index() when missing value is an error
Replacement Methods
Substitute parts of strings:
text = "I love Java. Java is great!"
# Replace all occurrences
new_text = text.replace("Java", "Python")
print(new_text) # "I love Python. Python is great!"
# Replace limited occurrences
partial = text.replace("Java", "Python", 1) # Replace only first
print(partial) # "I love Python. Java is great!"
# Chain replacements
messy = "Hello...World...!"
clean = messy.replace("...", " ")
print(clean) # "Hello World !"
Split and Join
Convert between strings and lists:
Splitting Strings
# Split by whitespace (default)
sentence = "Hello World Python"
words = sentence.split()
print(words) # ['Hello', 'World', 'Python']
# Split by specific delimiter
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
# Split with limit
text = "a-b-c-d-e"
parts = text.split("-", 2) # Split at most 2 times
print(parts) # ['a', 'b', 'c-d-e']
# Split lines
multiline = "Line 1\nLine 2\nLine 3"
lines = multiline.splitlines()
print(lines) # ['Line 1', 'Line 2', 'Line 3']
Joining Strings
words = ['Hello', 'World', 'Python']
# Join with space
sentence = " ".join(words)
print(sentence) # "Hello World Python"
# Join with comma
csv = ",".join(words)
print(csv) # "Hello,World,Python"
# Join with nothing
combined = "".join(words)
print(combined) # "HelloWorldPython"
# Join with newline
lines = "\n".join(words)
print(lines)
# Hello
# World
# Python
Visual: Split and Join
Split ↔ Join
SPLIT JOIN
"a,b,c".split(",") ",".join(['a','b','c'])
↓ ↓
['a', 'b', 'c'] → "a,b,c"
String → List List → String
(breaks apart) (puts together)
They are INVERSE operations!
Validation Methods
Check string characteristics:
# Check content type
print("hello".isalpha()) # True (only letters)
print("hello123".isalpha()) # False (has numbers)
print("12345".isdigit()) # True (only digits)
print("12.34".isdigit()) # False (has period)
print("hello123".isalnum()) # True (letters and/or numbers)
print("hello 123".isalnum()) # False (has space)
# Check case
print("HELLO".isupper()) # True
print("hello".islower()) # True
print("Hello World".istitle())# True
# Check whitespace
print(" ".isspace()) # True (only whitespace)
print(" hi ".isspace()) # False (has non-whitespace)
Validation Methods Summary
| Method | Returns True if... |
|---|---|
isalpha() |
All characters are letters |
isdigit() |
All characters are digits |
isalnum() |
All characters are letters or digits |
isspace() |
All characters are whitespace |
isupper() |
All letters are uppercase |
islower() |
All letters are lowercase |
istitle() |
String is title case |
Practical Examples
Example 1: Clean User Input
def clean_username(username):
"""Clean and validate a username."""
# Remove whitespace and convert to lowercase
cleaned = username.strip().lower()
# Check if valid (only letters and numbers)
if cleaned.isalnum():
return cleaned
else:
return None
# Test it
print(clean_username(" Alice123 ")) # "alice123"
print(clean_username(" Invalid User! ")) # None
Example 2: Parse CSV Data
def parse_csv_line(line):
"""Parse a CSV line into a dictionary."""
parts = line.strip().split(",")
return {
"name": parts[0].strip(),
"age": int(parts[1].strip()),
"city": parts[2].strip()
}
csv_line = " Alice , 25 , Paris "
person = parse_csv_line(csv_line)
print(person) # {'name': 'Alice', 'age': 25, 'city': 'Paris'}
Example 3: Text Statistics
def analyze_text(text):
"""Analyze text and return statistics."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase_letters": sum(1 for c in text if c.isupper()),
"lowercase_letters": sum(1 for c in text if c.islower())
}
sample = "Hello World! How are you? I am fine."
stats = analyze_text(sample)
print(stats)
# {'characters': 37, 'words': 8, 'sentences': 3, 'uppercase_letters': 4, ...}
Key Takeaways
Remember These Points
Case: upper(), lower(), title(), capitalize()
Trim: strip(), lstrip(), rstrip()
Essential for cleaning user input!
Search: find(), index(), count(), startswith(), endswith()
find() returns -1, index() raises error if not found
Replace: replace(old, new)
Returns new string, original unchanged
Split/Join: split() → list, join() → string
They are inverse operations!
Validate: isalpha(), isdigit(), isalnum(), isupper()...
Return True/False for checking content
ALL methods return NEW strings - originals unchanged!
What's Next?
You've learned to transform and analyze strings. But how do you create complex strings with variables mixed in? In the next lesson, we'll explore string formatting – elegant ways to build dynamic text with embedded values!
