📝 Text and Strings
Strings are Python's way of handling text data - from simple messages to complex document processing. Whether you're displaying information to users or processing file content, strings are fundamental to almost every program you'll write.
Python makes working with text intuitive and powerful, providing extensive tools for creating, modifying, and formatting strings.
# String basics
name = "Alice"
message = 'Hello, World!'
greeting = f"Welcome, {name}!"
print(name) # Alice
print(message) # Hello, World!
print(greeting) # Welcome, Alice!
🎯 Creating Strings
Strings are created by enclosing text in quotes. Python accepts different quote types, giving you flexibility in handling various text scenarios.
Quote Variations
# Different quote types
single_quote = 'Python is awesome'
double_quote = "It's a great language"
with_quotes = 'She said, "Hello there!"'
print(single_quote)
print(double_quote)
print(with_quotes)
Multi-line Strings
# Multi-line strings with triple quotes
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you!"""
print(poem)
📏 String Length and Access
Every string has a length you can measure, and you can access individual characters using their position (index). Python uses zero-based indexing.
# String length and character access
greeting = "Hello"
print(f"String: '{greeting}'")
print(f"Length: {len(greeting)}")
print(f"First character: '{greeting[0]}'")
print(f"Last character: '{greeting[-1]}'")
print(f"Middle character: '{greeting[2]}'")
🎨 String Formatting
The modern way to combine strings with variables is using f-strings (formatted string literals). They're readable, efficient, and support expressions.
Basic F-String Formatting
# F-strings for readable formatting
name = "Alice"
age = 25
city = "New York"
introduction = f"Hi, I'm {name}, {age} years old, from {city}"
print(introduction)
# With calculations
price = 29.99
quantity = 3
total = f"Total: ${price * quantity:.2f}"
print(total)
Advanced F-String Features
# Advanced f-string formatting
product = "Laptop"
price = 999.99
discount = 0.15
message = f"The {product} costs ${price:.2f}"
discounted = f"With {discount:.0%} off: ${price * (1-discount):.2f}"
grade = f"Grade: {'A' if 95 >= 90 else 'B'}"
print(message)
print(discounted)
print(grade)
Essential String Methods 🛠️
Python provides powerful methods for processing and manipulating text. These methods help you clean data, format output, and analyze text content.
Method | Purpose | Example |
---|---|---|
.upper() | Convert to uppercase | "hello".upper() → "HELLO" |
.lower() | Convert to lowercase | "HELLO".lower() → "hello" |
.strip() | Remove whitespace | " text ".strip() → "text" |
.replace(old, new) | Replace text | "hello".replace("l", "x") → "hexxo" |
.split(sep) | Split into list | "a,b,c".split(",") → ["a", "b", "c"] |
.find(sub) | Find position | "hello".find("ll") → 2 |
.startswith(prefix) | Check start | "hello".startswith("he") → True |
.endswith(suffix) | Check end | "hello".endswith("lo") → True |
Case Conversion
# Case conversion methods
text = "Hello World"
print(f"Original: {text}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}")
print(f"Title case: {text.title()}")
Text Cleaning
# Cleaning messy text
messy_text = " Hello World "
email = "User@Example.COM"
clean_text = messy_text.strip()
clean_email = email.strip().lower()
print(f"Cleaned text: '{clean_text}'")
print(f"Cleaned email: '{clean_email}'")
Finding and Replacing
# Text search and replacement
sentence = "I love cats and cats love me"
email = "user@example.com"
# Replace text
new_sentence = sentence.replace("cats", "dogs")
print(f"Original: {sentence}")
print(f"Modified: {new_sentence}")
# Find text position
at_position = email.find("@")
print(f"@ symbol at position: {at_position}")
# Check beginnings and endings
print(f"Starts with 'user': {email.startswith('user')}")
print(f"Ends with '.com': {email.endswith('.com')}")
🔍 String Validation
String methods help you validate and check the properties of text data.
# String validation examples
test_values = ["123", "abc", "ABC123", " ", "hello"]
for value in test_values:
print(f"'{value}': digit={value.isdigit()}, "
f"alpha={value.isalpha()}, alnum={value.isalnum()}")
# Practical validation
user_input = "john123"
filename = "document.pdf"
print(f"Username valid: {user_input.isalnum()}")
print(f"Is PDF file: {filename.endswith('.pdf')}")
✂️ String Slicing
String slicing lets you extract portions of text using [start:end]
syntax. This is powerful for text processing and data extraction.
# String slicing examples
text = "Python Programming"
phone = "123-456-7890"
email = "user@example.com"
print(f"First 6 chars: '{text[:6]}'")
print(f"Last 11 chars: '{text[7:]}'")
print(f"Every 2nd char: '{text[::2]}'")
print(f"Reversed: '{text[::-1]}'")
# Practical extraction
area_code = phone[:3]
username = email[:email.find("@")]
print(f"Area code: {area_code}")
print(f"Username: {username}")
📝 Quick String Practice
Let's practice working with text using simple string operations!
Hands-on Exercise
Practice basic string operations like cleaning text and using string methods.
# String Practice - Keep it simple!
# Format a name properly
messy_name = " john doe "
# Clean and format the name
clean_name = # TODO: Your code here (remove spaces and capitalize)
# Work with an email
email = "User@EXAMPLE.com"
# Make it lowercase
clean_email = # TODO: Your code here
# Get string length
message = "Hello Python!"
# Count the characters
message_length = # TODO: Your code here
# Print results
print(f"Clean name: {clean_name}")
print(f"Clean email: {clean_email}")
print(f"Message length: {message_length}")
Solution and Explanation 💡
Click to see the complete solution
# String Practice - Simple solution
# Format a name properly
messy_name = " john doe "
# Clean and format the name
clean_name = messy_name.strip().title()
# Work with an email
email = "User@EXAMPLE.com"
# Make it lowercase
clean_email = email.lower()
# Get string length
message = "Hello Python!"
# Count the characters
message_length = len(message)
# Print results
print(f"Clean name: {clean_name}")
print(f"Clean email: {clean_email}")
print(f"Message length: {message_length}")
Key Learning Points:
- 📌 String Methods: Used
.strip()
,.title()
,.lower()
- 📌 String Length: Used
len()
to count characters - 📌 Text Cleaning: Removed extra spaces and fixed capitalization
💬 Working with User Input
User input always comes as strings. You'll often need to clean and process this input for your programs.
# Processing user input (simulated)
user_inputs = [" Alice ", "25", "alice@email.com"]
# Clean and process
name = user_inputs[0].strip().title()
age_text = user_inputs[1].strip()
email = user_inputs[2].strip().lower()
print(f"Processed name: {name}")
print(f"Age (as text): {age_text}")
print(f"Email: {email}")
# Convert age to number (covered in Converting Types)
age = int(age_text)
print(f"Age (as number): {age}")
🎯 Key Takeaways
🧠 Test Your Knowledge
Ready to test your understanding of text and strings?
🚀 What's Next?
Now that you understand strings, let's explore boolean values - Python's way of handling true/false decisions that control program logic.
Learn about True/False Values to understand decision-making, or jump ahead to Converting Types to learn about transforming data between different types.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.