Strings are sequences of characters - they're how we work with text in Python. Whether it's a username, a message, a file path, or the contents of a book, strings are everywhere!
Python gives you multiple ways to create strings:
There's no difference between single and double quotes in Python! Use whichever is more convenient. If your string contains one type of quote, use the other type to wrap it.
What if you need special characters inside a string? Use the backslash \ to "escape" them:
For file paths or regex, raw strings (prefix with r) treat backslashes literally:
Practice creating different types of strings. Pay attention to when you need to escape characters!
Create a string called dialogue that contains: He asked, "What's your name?" and print it.
You know how to create strings. Let's learn to access individual characters!
Strings are sequences - each character has a position (index). Python uses zero-based indexing, meaning the first character is at position 0.
Negative: -6, -5, -4, -3, -2, -1 (from end)
Negative indices count from the end! -1 is the last character, -2 is second to last, etc. This is super useful when you don't know the string's length.
Extract a substring using string[start:stop:step]. The start is included, stop is excluded!
text[::-1] is the Pythonic way to reverse a string! The -1 step means "go backwards one character at a time".
Use indexing and slicing to extract parts of a string. No loops needed!
Given email = "wizard@hexworth.edu", extract and print:
1. The username (before @)
2. The domain (after @)
3. The entire email reversed
You can extract any part of a string. Now let's learn powerful string methods!
Strings come with dozens of built-in methods - functions that belong to the string object. Call them with string.method().
String methods never modify the original string - they return a new string. This is because strings are immutable (unchangeable) in Python.
| Method | Description | Example |
|---|---|---|
.upper() |
Convert to uppercase | "hello".upper() → "HELLO" |
.lower() |
Convert to lowercase | "HELLO".lower() → "hello" |
.capitalize() |
Capitalize first letter | "hello world".capitalize() → "Hello world" |
.title() |
Capitalize each word | "hello world".title() → "Hello World" |
.swapcase() |
Swap upper/lower | "HeLLo".swapcase() → "hEllO" |
split() breaks a string into a list. join() combines a list into a string. They're perfect for text processing!
Use string methods to clean and transform text. Chain multiple methods for powerful results!
Given raw = " HELLO world ":
1. Strip whitespace
2. Convert to title case
3. Print the result (should be "Hello World")
You know the essential string methods. Let's explore formatting techniques!
We covered f-strings in Chapter 1. Now let's explore all the ways Python lets you format strings!
The modern, readable way to format strings (Python 3.6+):
Inside {value:spec}:
.2f = 2 decimal places (float)
05d = 5-digit zero-padded (int)
>10 = right-align in 10 chars
^10 = center in 10 chars
Joining strings together with +:
Older style (pre-Python 3.6), but still useful:
Use f-strings with format specifiers to create a nicely formatted receipt!
Given item="Widget", price=19.99, qty=3:
Print a line like: "Widget x3 $59.97"
(Item left-aligned 15 chars, total with 2 decimals)
You can format strings beautifully. One more section on operations!
Beyond methods, Python provides operators and functions for working with strings.
| 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 |
These methods are perfect for validating user input! Check if a password has letters, if a phone number has only digits, if a name has no numbers, etc.
Use string operations to validate a password. Check length, content, and more!
Given password = "Secure123", check if it:
1. Has at least 8 characters (use len())
2. Is alphanumeric (use isalnum())
Print "Valid!" if both are true, "Invalid!" otherwise.
You've mastered string operations. Time for the summary!
Congratulations! You've completed Chapter 2 and mastered Python strings. Let's recap what you've learned:
Index 0 is first char, -1 is last. Slice with [start:stop:step].
Strings are immutable - methods return NEW strings!
f"text {var:.2f}" for clean, readable formatting.
isdigit(), isalpha(), isalnum() for input validation.
You've mastered Python strings. Ready to prove your skills?