guidebeginner15 min
Strings: Working with Text
Master string manipulation: searching, splitting, formatting, and more.
Prerequisites
Last updated: Jan 28, 2026
We've used strings since the beginning, but there's a lot more you can do with them. Strings are actually sequences (like lists) and have many useful methods.
Strings Are Sequences
python
message = "Hello, World!"
# Indexing (same as lists)
print(message[0]) # H
print(message[-1]) # !
# Slicing
print(message[0:5]) # Hello
print(message[7:]) # World!
# Length
print(len(message)) # 13
# Iteration
for char in message:
print(char)
# Check membership
print("World" in message) # True
print("world" in message) # False (case-sensitive)Case Methods
python
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.title()) # Hello, World!
print(text.capitalize()) # Hello, world!
print(text.swapcase()) # hELLO, wORLD!Search and Replace
python
text = "Hello, World!"
# Find position (returns -1 if not found)
print(text.find("World")) # 7
print(text.find("Python")) # -1
# Count occurrences
print(text.count("l")) # 3
# Replace
print(text.replace("World", "Python")) # Hello, Python!
# Starts/ends with
print(text.startswith("Hello")) # True
print(text.endswith("!")) # TrueSplit and Join
python
# Split string into list
sentence = "The quick brown fox"
words = sentence.split() # Split on whitespace
print(words) # ['The', 'quick', 'brown', 'fox']
# Split on specific character
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
# Join list into string
words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence) # Hello World
path_parts = ["users", "alice", "documents"]
path = "/".join(path_parts)
print(path) # users/alice/documentsStrip Whitespace
python
messy = " Hello, World! "
print(messy.strip()) # "Hello, World!" (both sides)
print(messy.lstrip()) # "Hello, World! " (left only)
print(messy.rstrip()) # " Hello, World!" (right only)
# Strip specific characters
text = "...Hello..."
print(text.strip(".")) # "Hello"String Formatting
python
name = "Alice"
age = 25
price = 19.99
# f-strings (recommended)
print(f"Name: {name}, Age: {age}")
# Format numbers
print(f"Price: ${price:.2f}") # Price: $19.99
print(f"Percentage: {0.856:.1%}") # Percentage: 85.6%
print(f"Padded: {42:05d}") # Padded: 00042
# Align text
print(f"{'left':<10}|") # left |
print(f"{'right':>10}|") # | right|
print(f"{'center':^10}|") # center |Validation Methods
python
# Check string content
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
print("Hello".istitle()) # True
print("HELLO".isupper()) # True
print("hello".islower()) # TruePractical Example: Clean User Input
python
def clean_input(user_input):
"""Clean and validate user input."""
# Remove whitespace
cleaned = user_input.strip()
# Standardize case
cleaned = cleaned.lower()
# Remove extra spaces
cleaned = " ".join(cleaned.split())
return cleaned
# Test it
messy_input = " HELLO World "
print(clean_input(messy_input)) # "hello world"Practice
- Write a function that counts words in a sentence
- Check if a string is a palindrome (reads same forwards and backwards)
- Extract all email addresses from a text (hint: look for @ and split)
- Convert "hello_world" to "HelloWorld" (snake_case to PascalCase)
- Censor bad words in a string by replacing them with asterisks
Related documentation