Python String Methods: Essential Guide with Examples
Python strings have powerful built-in methods that make text manipulation easy. Here are the most essential ones you'll use every day:
1. Case Conversion Methods
text = "Hello World"
# Convert to uppercase
text.upper() # "HELLO WORLD"
# Convert to lowercase
text.lower() # "hello world"
# Title case (capitalize each word)
text.title() # "Hello World"
"hello world".title() # "Hello World"
# Capitalize first letter only
"hello world".capitalize() # "Hello world"
# Swap case
"Hello World".swapcase() # "hELLO wORLD"
2. strip() - Remove Whitespace
# Remove leading and trailing whitespace ✅
text = " hello world "
text.strip() # "hello world"
# Remove only from left
text.lstrip() # "hello world "
# Remove only from right
text.rstrip() # " hello world"
# Remove specific characters
"###Hello###".strip('#') # "Hello"
"...python...".strip('.') # "python"
# Common use: Clean user input
user_input = input().strip() # Remove extra spaces
3. split() and join()
# Split string into list
text = "apple,banana,cherry"
fruits = text.split(',') # ['apple', 'banana', 'cherry']
# Split on whitespace (default)
"hello world python".split() # ['hello', 'world', 'python']
# Limit splits
"a-b-c-d".split('-', 2) # ['a', 'b', 'c-d']
# Split lines
multiline = "line1\nline2\nline3"
lines = multiline.splitlines() # ['line1', 'line2', 'line3']
# Join list into string ✅
words = ['hello', 'world']
' '.join(words) # "hello world"
','.join(words) # "hello,world"
'\n'.join(words) # "hello\nworld"
4. replace() - Substitute Text
# Replace substring
text = "Hello World"
text.replace('World', 'Python') # "Hello Python"
# Replace all occurrences
text = "apple apple apple"
text.replace('apple', 'orange') # "orange orange orange"
# Limit replacements
text.replace('apple', 'orange', 2) # "orange orange apple"
# Remove characters (replace with empty string)
"hello123world".replace('123', '') # "helloworld"
# Chain replacements
text = "a-b-c"
text.replace('-', ' ').replace(' ', '_') # "a_b_c"
5. find() and index() - Search
text = "Hello World"
# find() - returns index or -1 if not found ✅
text.find('World') # 6
text.find('xyz') # -1
# index() - returns index or raises ValueError
text.index('World') # 6
# text.index('xyz') # ValueError!
# Find from right
text.rfind('o') # 7 (last 'o')
text.rindex('o') # 7
# Check if substring exists (better than find)
if 'World' in text:
print("Found!")
# Count occurrences
"hello world".count('l') # 3
"banana".count('na') # 2
6. startswith() and endswith()
# Check prefix
filename = "report.pdf"
filename.startswith('report') # True
filename.startswith('data') # False
# Check suffix
filename.endswith('.pdf') # True
filename.endswith('.csv') # False
# Multiple options (tuple)
filename.endswith(('.pdf', '.doc', '.txt')) # True
# Practical: Filter files
files = ['data.csv', 'image.png', 'report.pdf']
csv_files = [f for f in files if f.endswith('.csv')]
# Check URL
url = "https://example.com"
if url.startswith(('http://', 'https://')):
print("Valid URL")
7. String Formatting
# f-strings (Python 3.6+) ✅ Best!
name = "Alice"
age = 30
print(f"{name} is {age} years old")
# "Alice is 30 years old"
# Format with expressions
print(f"{name.upper()} is {age + 1} next year")
# Format numbers
price = 19.99
print(f"Price: ${price:.2f}") # "Price: $19.99"
# .format() method
"Hello {}, you are {}".format(name, age)
"Hello {name}, age {age}".format(name="Bob", age=25)
# % formatting (old style)
"Hello %s, you are %d" % (name, age)
8. Checking String Content
# Check if alphanumeric
"Hello123".isalnum() # True
"Hello 123".isalnum() # False (space)
# Check if alphabetic
"Hello".isalpha() # True
"Hello123".isalpha() # False
# Check if numeric
"12345".isdigit() # True
"123.45".isdigit() # False
# Check if lowercase/uppercase
"hello".islower() # True
"HELLO".isupper() # True
# Check if whitespace
" ".isspace() # True
" a ".isspace() # False
9. Padding and Alignment
# Center text
"hello".center(10) # " hello "
"hello".center(10, '*') # "**hello***"
# Left justify
"hello".ljust(10) # "hello "
"hello".ljust(10, '-') # "hello-----"
# Right justify
"hello".rjust(10) # " hello"
"hello".rjust(10, '0') # "00000hello"
# Zero padding for numbers
"42".zfill(5) # "00042"
"-42".zfill(5) # "-0042"
10. Practical Examples
# Clean and normalize email
email = " [email protected] "
clean_email = email.strip().lower() # "[email protected]"
# Parse CSV line
line = "John,25,NYC"
name, age, city = line.split(',')
# Extract filename from path
path = "/home/user/documents/file.txt"
filename = path.split('/')[-1] # "file.txt"
basename = filename.split('.')[0] # "file"
# Create slug from title
title = "Hello World - Python Tutorial!"
slug = title.lower().replace(' ', '-').replace('!', '')
# "hello-world---python-tutorial"
# Validate password
password = "MyPassword123"
is_valid = (len(password) >= 8 and
any(c.isupper() for c in password) and
any(c.isdigit() for c in password))
# Parse key-value pairs
config = "name=John;age=30;city=NYC"
pairs = [pair.split('=') for pair in config.split(';')]
config_dict = dict(pairs)
# {'name': 'John', 'age': '30', 'city': 'NYC'}
Best Practices
- ✅ Use f-strings for formatting (Python 3.6+) - fastest and most readable
- ✅ Use
strip()on user input to remove extra whitespace - ✅ Use
inoperator instead offind() != -1 - ✅ Use
join()to concatenate many strings (much faster than +) - ✅ Use
startswith()/endswith()for prefix/suffix checks - ❌ Don't use + in loops to build strings (use list + join instead)
- ❌ Don't use
index()without try/except (usefind()instead) - ⚠️ Remember: strings are immutable - methods return new strings
Pro Tip: When building a string from many parts in a loop, collect them in a list and use join() at the end. It's 10-100x faster than concatenating with + because strings are immutable in Python!