String Functions and Methods
What Are String Methods?
String methods are built-in functions that work specifically with text (strings). They let you transform, check, or manipulate strings easily.
Syntax:
result = text.method_name()
The method comes after the string variable with a dot (.) in between.
Example:
name = "Alice"
name_upper = name.upper() # Convert to uppercase
print(name_upper) # Output: ALICE
Important: Most string methods don’t change the original string - they return a new string with the changes.
greeting = "hello"
greeting.upper() # Returns "HELLO" but doesn't change greeting
print(greeting) # Still prints: hello
# To keep the change, assign it to a variable:
greeting_upper = greeting.upper()
print(greeting_upper) # Prints: HELLO
Common String Methods
Case Conversion Methods
| Method | What It Does | Example | Result |
|---|---|---|---|
.upper() |
Convert all letters to UPPERCASE | "hello".upper() |
"HELLO" |
.lower() |
Convert all letters to lowercase | "HELLO".lower() |
"hello" |
.capitalize() |
Capitalize only the first letter | "hello world".capitalize() |
"Hello world" |
.title() |
Capitalize the first letter of each word | "hello world".title() |
"Hello World" |
Examples:
city = "new york"
print(city.upper()) # NEW YORK
print(city.capitalize()) # New york
print(city.title()) # New York
# Original string unchanged
print(city) # new york
Common use case: Making comparisons case-insensitive
user_answer = input("Continue? (yes/no): ")
# This works regardless of how user types it: "YES", "Yes", "yes"
if user_answer.lower() == "yes":
print("Continuing...")
← Back to where you were | → Start the course from the beginning
Whitespace Methods
| Method | What It Does | Example | Result |
|---|---|---|---|
.strip() |
Remove spaces from both ends | " hello ".strip() |
"hello" |
.lstrip() |
Remove spaces from left end only | " hello ".lstrip() |
"hello " |
.rstrip() |
Remove spaces from right end only | " hello ".rstrip() |
" hello" |
Examples:
messy_name = " Alice "
clean_name = messy_name.strip()
print(f"'{clean_name}'") # 'Alice'
Common use case: Cleaning user input
name = input("Enter your name: ").strip()
# User types: " Bob " (with spaces)
# name becomes: "Bob" (spaces removed)
← Back to where you were | → Start the course from the beginning
—
Checking String Content
| Method | What It Does | Returns | Example |
|---|---|---|---|
.isdigit() |
Check if all characters are digits | True or False |
"123".isdigit() → True |
.isalpha() |
Check if all characters are letters | True or False |
"abc".isalpha() → True |
.isalnum() |
Check if all characters are letters or digits | True or False |
"abc123".isalnum() → True |
.isspace() |
Check if all characters are whitespace | True or False |
" ".isspace() → True |
Examples:
"123".isdigit() # True
"12.5".isdigit() # False (decimal point)
"abc".isdigit() # False (letters)
"-5".isdigit() # False (minus sign)
"hello".isalpha() # True
"hello123".isalpha() # False (has numbers)
"hello ".isalpha() # False (has space)
Common use case: Validating input
age_input = input("Enter your age: ")
if age_input.isdigit():
age = int(age_input)
print(f"Your age: {age}")
else:
print("Please enter only numbers!")
← Back to where you were | → Start the course from the beginning
—
Finding and Replacing
| Method | What It Does | Example | Result |
|---|---|---|---|
.startswith(text) |
Check if string starts with text | "hello".startswith("he") |
True |
.endswith(text) |
Check if string ends with text | "hello".endswith("lo") |
True |
.count(text) |
Count how many times text appears | "hello".count("l") |
2 |
.replace(old, new) |
Replace old text with new text | "hello".replace("l", "r") |
"herro" |
Examples:
filename = "report.pdf"
print(filename.endswith(".pdf")) # True
print(filename.endswith(".doc")) # False
sentence = "I love Python and Python is great"
print(sentence.count("Python")) # 2
message = "Hello World"
new_message = message.replace("World", "Python")
print(new_message) # Hello Python
Common use case: File extension checking
filename = input("Enter filename: ")
if filename.endswith(".py"):
print("This is a Python file!")
elif filename.endswith(".txt"):
print("This is a text file!")
else:
print("Unknown file type")
← Back to where you were | → Start the course from the beginning
—
Splitting and Joining
| Method | What It Does | Example | Result |
|---|---|---|---|
.split() |
Split string into a list | "a b c".split() |
["a", "b", "c"] |
.split(separator) |
Split by specific separator | "a,b,c".split(",") |
["a", "b", "c"] |
separator.join(list) |
Join list items with separator | "-".join(["a", "b"]) |
"a-b" |
Examples:
# Split by spaces (default)
sentence = "Hello my friend"
words = sentence.split()
print(words) # ["Hello", "my", "friend"]
# Split by comma
data = "apple,banana,orange"
fruits = data.split(",")
print(fruits) # ["apple", "banana", "orange"]
# Join list into string
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence) # Python is fun
# Join with different separator
words = ["apple", "banana", "orange"]
result = ", ".join(words)
print(result) # apple, banana, orange
Common use case: Processing comma-separated input
colors_input = input("Enter your favorite colors (comma-separated): ")
# User types: "red, blue, green"
colors = colors_input.split(",")
# Result: ["red", " blue", " green"]
# Clean up spaces
colors = [color.strip() for color in colors]
# Result: ["red", "blue", "green"]
← Back to where you were | → Start the course from the beginning
—
Chaining Methods
You can chain multiple methods together:
messy_text = " HELLO WORLD "
clean_text = messy_text.strip().lower().capitalize()
print(clean_text) # Hello world
# Step by step:
# 1. strip() → "HELLO WORLD"
# 2. lower() → "hello world"
# 3. capitalize() → "Hello world"
Common use case: Clean and normalize user input
answer = input("Continue? (yes/no): ").strip().lower()
if answer == "yes":
print("Continuing...")
elif answer == "no":
print("Stopping...")
else:
print("Please enter yes or no")
← Back to where you were | → Start the course from the beginning
—
Practical Examples
Example 1: Username Validation
username = input("Create username: ").strip()
if not username:
print("Username cannot be empty!")
elif not username.isalnum():
print("Username must be letters and numbers only!")
elif len(username) < 3:
print("Username must be at least 3 characters!")
else:
print(f"Username '{username}' created successfully!")
Example 2: Clean and Format Name
name = input("Enter your full name: ").strip().title()
print(f"Hello, {name}!")
# User types: " alice SMITH "
# Output: Hello, Alice Smith!
Example 3: Parse Email
email = input("Enter email: ").strip().lower()
if "@" not in email:
print("Invalid email - missing @")
elif not email.endswith((".com", ".org", ".edu")):
print("Invalid email - must end with .com, .org, or .edu")
else:
username = email.split("@")[0]
domain = email.split("@")[1]
print(f"Username: {username}")
print(f"Domain: {domain}")
Example 4: Count Words
sentence = input("Enter a sentence: ").strip()
words = sentence.split()
word_count = len(words)
print(f"Your sentence has {word_count} words")
← Back to where you were | → Start the course from the beginning
—
Quick Reference Table
| Category | Methods |
|---|---|
| Case | .upper(), .lower(), .capitalize(), .title() |
| Whitespace | .strip(), .lstrip(), .rstrip() |
| Check Type | .isdigit(), .isalpha(), .isalnum(), .isspace() |
| Find | .startswith(), .endswith(), .count() |
| Transform | .replace(), .split(), .join() |
← Back to where you were | → Start the course from the beginning
—
Remember
Strings are immutable:
name = "alice"
name.upper() # Returns "ALICE" but doesn't change name
print(name) # Still "alice"
# To save the change:
name = name.upper()
print(name) # Now "ALICE"
Methods return new strings:
original = "hello"
modified = original.upper()
print(original) # hello (unchanged)
print(modified) # HELLO (new string)
Empty strings are falsy:
text = " ".strip() # Results in ""
if text:
print("Has content")
else:
print("Empty!") # This runs
← Back to where you were | → Start the course from the beginning
—
Summary
Key takeaways:
- String methods transform or check strings
- Methods don’t change the original string - they return a new one
- Save the result if you want to keep changes:
text = text.upper() - Chain methods for multiple operations:
.strip().lower() - Use for validation - check user input before processing
Useful functions
.lower()- Compare text case-insensitively.strip()- Remove unwanted spaces.isdigit()- Check if input is a number.split()- Break text into pieces.replace()- Swap text
← Back to where you were | → Start the course from the beginning
