← Zero to Python Chapter 2: Strings
0% Complete

String Basics

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!

Creating Strings

Python gives you multiple ways to create strings:

strings.py Python
# Single quotes name = 'Alice' # Double quotes (same as single) greeting = "Hello, World!" # Triple quotes for multi-line strings poem = """Roses are red, Violets are blue, Python is awesome, And so are you!""" # Mixing quotes (useful for including quotes in strings) message = "She said 'Hello!'" another = 'He replied "Hi there!"'

Single vs Double Quotes

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.

Escape Characters

What if you need special characters inside a string? Use the backslash \ to "escape" them:

escapes.py Python
# Newline two_lines = "First line\nSecond line" print(two_lines) # Tab tabbed = "Name:\tAlice" print(tabbed) # Backslash itself path = "C:\\Users\\Alice\\Documents" # Quote inside string quote = "She said \"Hello!\""
First line Second line Name: Alice

Raw Strings

For file paths or regex, raw strings (prefix with r) treat backslashes literally:

raw_strings.py Python
# Regular string (need double backslash) path1 = "C:\\Users\\Documents\\file.txt" # Raw string (backslash is literal) path2 = r"C:\Users\Documents\file.txt" # Both produce the same result! print(path1 == path2) # True

Lab Exercise 1: String Creation

Beginner

Instructions

Practice creating different types of strings. Pay attention to when you need to escape characters!

Your Task

Create a string called dialogue that contains: He asked, "What's your name?" and print it.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: String Basics Complete!

You know how to create strings. Let's learn to access individual characters!

Indexing & Slicing

Strings are sequences - each character has a position (index). Python uses zero-based indexing, meaning the first character is at position 0.

String Indexing

Index Visualization: "Python"

P
0
y
1
t
2
h
3
o
4
n
5

Negative: -6, -5, -4, -3, -2, -1 (from end)

indexing.py Python
word = "Python" # Positive indexing (from start) print(word[0]) # 'P' - first character print(word[1]) # 'y' - second character print(word[5]) # 'n' - last character # Negative indexing (from end) print(word[-1]) # 'n' - last character print(word[-2]) # 'o' - second to last print(word[-6]) # 'P' - first character

Negative Indexing

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.

String Slicing

Extract a substring using string[start:stop:step]. The start is included, stop is excluded!

slicing.py Python
text = "Hello, World!" # Basic slicing [start:stop] print(text[0:5]) # 'Hello' - chars 0-4 print(text[7:12]) # 'World' - chars 7-11 # Omit start or stop print(text[:5]) # 'Hello' - from beginning print(text[7:]) # 'World!' - to end print(text[:]) # 'Hello, World!' - copy all # With step [start:stop:step] print(text[::2]) # 'Hlo ol!' - every 2nd char print(text[::-1]) # '!dlroW ,olleH' - REVERSED! # Negative indices in slicing print(text[-6:-1]) # 'World' - last 6 chars except last

Reverse a String

text[::-1] is the Pythonic way to reverse a string! The -1 step means "go backwards one character at a time".

Lab Exercise 2: String Surgery

Beginner

Instructions

Use indexing and slicing to extract parts of a string. No loops needed!

Your Task

Given email = "wizard@hexworth.edu", extract and print:
1. The username (before @)
2. The domain (after @)
3. The entire email reversed

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Indexing Mastered!

You can extract any part of a string. Now let's learn powerful string methods!

String Methods

Strings come with dozens of built-in methods - functions that belong to the string object. Call them with string.method().

Strings are Immutable!

String methods never modify the original string - they return a new string. This is because strings are immutable (unchangeable) in Python.

Case Methods

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"

Search Methods

search.py Python
text = "Hello, World!" # Find position of substring (-1 if not found) print(text.find("World")) # 7 print(text.find("Python")) # -1 (not found) # Check if string starts/ends with print(text.startswith("Hello")) # True print(text.endswith("!")) # True # Count occurrences print("banana".count("a")) # 3

Modification Methods

modify.py Python
# Replace substrings msg = "Hello, World!" print(msg.replace("World", "Python")) # Hello, Python! # Strip whitespace messy = " extra spaces " print(messy.strip()) # "extra spaces" print(messy.lstrip()) # "extra spaces " (left only) print(messy.rstrip()) # " extra spaces" (right only) # Split into list sentence = "one,two,three" print(sentence.split(",")) # ['one', 'two', 'three'] # Join list into string words = ["Python", "is", "awesome"] print(" ".join(words)) # "Python is awesome"

Split and Join are Opposites

split() breaks a string into a list. join() combines a list into a string. They're perfect for text processing!

Lab Exercise 3: Text Processing

Intermediate

Instructions

Use string methods to clean and transform text. Chain multiple methods for powerful results!

Your Task

Given raw = " HELLO world ":
1. Strip whitespace
2. Convert to title case
3. Print the result (should be "Hello World")

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Methods Mastered!

You know the essential string methods. Let's explore formatting techniques!

String Formatting

We covered f-strings in Chapter 1. Now let's explore all the ways Python lets you format strings!

f-strings (Recommended)

The modern, readable way to format strings (Python 3.6+):

fstrings.py Python
name = "Alice" age = 25 balance = 1234.5678 # Basic f-string print(f"Hi, I'm {name}!") # Expressions inside {} print(f"Next year: {age + 1}") print(f"Uppercase: {name.upper()}") # Format specifiers print(f"Balance: ${balance:.2f}") # 2 decimals: $1234.57 print(f"Padded: {age:05d}") # Zero-pad: 00025 print(f"Right align: {name:>10}") # " Alice" print(f"Left align: {name:<10}") # "Alice " print(f"Center: {name:^10}") # " Alice "

Format Specifier Mini-Language

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

String Concatenation

Joining strings together with +:

concat.py Python
first = "Hello" second = "World" # Simple concatenation result = first + " " + second print(result) # "Hello World" # Repeat with * border = "=" * 20 print(border) # "====================" # Build gradually message = "" message += "Line 1\n" message += "Line 2\n" print(message)

The .format() Method

Older style (pre-Python 3.6), but still useful:

format_method.py Python
# Positional arguments print("{} + {} = {}".format(2, 3, 5)) # Named arguments print("{name} is {age} years old".format(name="Bob", age=30)) # Index arguments print("{0} vs {1}: {0} wins!".format("Python", "Java"))

Lab Exercise 4: Receipt Generator

Intermediate

Instructions

Use f-strings with format specifiers to create a nicely formatted receipt!

Your Task

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)

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Formatting Complete!

You can format strings beautifully. One more section on operations!

String Operations

Beyond methods, Python provides operators and functions for working with strings.

Length & Membership

operations.py Python
text = "Hello, World!" # Length print(len(text)) # 13 characters # Membership (in / not in) print("World" in text) # True print("Python" in text) # False print("xyz" not in text) # True # Comparison print("apple" < "banana") # True (alphabetical) print("A" < "a") # True (uppercase first)

Checking String Content

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
validation.py Python
# Input validation example username = "wizard123" pin = "4567" print(username.isalnum()) # True (letters and digits) print(pin.isdigit()) # True (all digits) print(len(pin) == 4) # True (4 digits) # Real validation if pin.isdigit() and len(pin) == 4: print("Valid PIN!")

Input Validation

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.

Lab Exercise 5: Password Validator

Intermediate

Instructions

Use string operations to validate a password. Check length, content, and more!

Your Task

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.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Operations Complete!

You've mastered string operations. Time for the summary!

Chapter 2 Summary

Congratulations! You've completed Chapter 2 and mastered Python strings. Let's recap what you've learned:

What You Learned

  • String Creation: Single, double, and triple quotes; escape characters; raw strings
  • Indexing & Slicing: Zero-based indexing, negative indices, slice notation [start:stop:step]
  • String Methods: upper(), lower(), strip(), split(), join(), replace(), find()
  • Formatting: f-strings with format specifiers, concatenation, .format() method
  • Operations: len(), in/not in, validation methods (isdigit, isalpha, etc.)

Key Takeaways

Indexing

Index 0 is first char, -1 is last. Slice with [start:stop:step].

Methods

Strings are immutable - methods return NEW strings!

f-strings

f"text {var:.2f}" for clean, readable formatting.

Validation

isdigit(), isalpha(), isalnum() for input validation.

Chapter 2 Complete!

You've mastered Python strings. Ready to prove your skills?

Take the Chapter 2 Practical Exam