Chapter 3: Working with Text 📝

Numbers are powerful, but text is where programs really come alive! Imagine apps, games, and websites without words — they wouldn’t make much sense. In Python, we call text strings, and they’re one of the most important data types you’ll work with.


Strings: Text Basics 💬

A string is simply a sequence of characters — letters, numbers, symbols, spaces, anything you can type! You create strings by wrapping text in quotation marks.

Creating Strings

You can use either single quotes (') or double quotes ("):

message = "Hello, Python!"
name = 'Jordan'
favorite_quote = "To infinity and beyond!"

Both work exactly the same way. Most Python programmers use double quotes, but the choice is yours. The important thing is to be consistent in your code.

Why have both? It makes it easier to include quotes inside your text:

# Using double quotes to include single quotes (apostrophes)
sentence = "It's a beautiful day!"

# Using single quotes to include double quotes
dialogue = 'She said, "Python is awesome!"'

What Can Strings Contain?

Strings can hold almost anything:

letters = "abc"
numbers_as_text = "12345"  # Notice: these are text, not actual numbers!
symbols = "!@#$%"
spaces = "   "  # Even empty space counts!
mixed = "Player1 scored 100 points!"

Important distinction: "42" is a string (text), while 42 is a number (integer). They look similar but behave differently:

age_as_number = 18
age_as_string = "18"

print(age_as_number + 2)   # Shows: 20 (math works)
print(age_as_string + "2") # Shows: 182 (joins text together)

Multi-Line Strings

Sometimes you need text that spans multiple lines. Use triple quotes for this:

poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""

print(poem)

This preserves line breaks exactly as you typed them, making it perfect for longer text, poems, or formatted messages.


Combining Strings: Building Text 🔗

One of the most useful things you can do with strings is combine them. Python gives you several ways to do this.

Concatenation (Joining Strings)

Concatenation means joining strings together using the + operator. Think of it like linking chains together — each piece connects to form something longer.

first_name = "Alex"
last_name = "Chen"
full_name = first_name + " " + last_name
print(full_name)  # Shows: Alex Chen

Notice we added " " (a space) between the names. Without it, we’d get “AlexChen” — Python doesn’t add spaces automatically!

You can concatenate as many strings as you want:

greeting = "Hello" + ", " + "my" + " " + "friend" + "!"
print(greeting)  # Shows: Hello, my friend!

Important: You can only concatenate strings with other strings. Mixing strings and numbers causes an error:

# This causes an error!
message = "I have " + 5 + " apples"

# Fix it by converting the number to a string
message = "I have " + str(5) + " apples"
print(message)  # Shows: I have 5 apples

Repetition (Repeating Strings)

Want to repeat a string multiple times? Use the * operator. This is incredibly handy for creating patterns or emphasis:

laugh = "ha" * 3
print(laugh)  # Shows: hahaha

separator = "=" * 20
print(separator)  # Shows: ====================

cheer = "Go team! " * 4
print(cheer)  # Shows: Go team! Go team! Go team! Go team! 

Think of it like stamping: you have a stamp (the string) and you’re stamping it onto paper multiple times.


String Methods: Text Superpowers 🦸

Strings come with built-in methods — special functions that can transform or analyze your text. A method is like a tool specifically designed to work with strings. You call a method by putting a dot after your string, then the method name.

Let’s explore some of the most useful ones!

Changing Case

These methods change the capitalization of your text without modifying the original string (they return a new version):

message = "Hello, World!"

uppercase = message.upper()
print(uppercase)  # Shows: HELLO, WORLD!

lowercase = message.lower()
print(lowercase)  # Shows: hello, world!

titlecase = message.title()
print(titlecase)  # Shows: Hello, World!

When is this useful?

  • Making comparisons case-insensitive (usernames, passwords)
  • Formatting headings or titles
  • Ensuring consistency in data
# Case-insensitive comparison
user_input = "YES"
if user_input.lower() == "yes":
    print("User agreed!")  # This runs!

Removing Whitespace

Whitespace means spaces, tabs, and line breaks. The .strip() family of methods removes unwanted whitespace — super helpful when dealing with user input:

messy_text = "   Hello!   "

cleaned = messy_text.strip()
print(cleaned)  # Shows: "Hello!" (removed spaces from both sides)

left_cleaned = messy_text.lstrip()
print(left_cleaned)  # Shows: "Hello!   " (removed left spaces only)

right_cleaned = messy_text.rstrip()
print(right_cleaned)  # Shows: "   Hello!" (removed right spaces only)

Real-world example:

# User accidentally adds spaces when typing their name
name = input("Enter your name: ")  # User types: "  Jordan  "
name = name.strip()  # Now it's "Jordan" — clean!
print("Welcome,", name)

Other Useful Methods

There are many more string methods. Here are a few worth knowing:

text = "Python is fun"

# Replace text
new_text = text.replace("fun", "awesome")
print(new_text)  # Shows: Python is awesome

# Count occurrences
count = text.count("n")
print(count)  # Shows: 2 (appears in "Python" and "fun")

# Check what a string starts or ends with
print(text.startswith("Python"))  # Shows: True
print(text.endswith("fun"))       # Shows: True

# Find position of a substring
position = text.find("is")
print(position)  # Shows: 7 (starts at index 7)

Remember: Methods don’t change the original string — they return a new one! If you want to keep the change, store it in a variable:

name = "alice"
name = name.upper()  # Now name is "ALICE"
print(name)

F-Strings: Formatting Text Beautifully ✨

F-strings are Python’s modern, elegant way to combine variables and text. They’re called “formatted string literals,” but everyone just calls them f-strings. They make your code cleaner and easier to read.

The Basic Syntax

Put an f before the opening quote, then use curly braces {} to insert variables directly into your text:

name = "Jordan"
age = 14
message = f"Hi, I'm {name} and I'm {age} years old."
print(message)  # Shows: Hi, I'm Jordan and I'm 14 years old.

The f tells Python: “This is a special string where {} will be replaced with actual values.”

Why Are F-Strings Great?

Compare the old way to the f-string way:

name = "Alex"
score = 95

# Old way: using concatenation (messy and hard to read)
message = "Player " + name + " scored " + str(score) + " points!"

# F-string way: clean and readable
message = f"Player {name} scored {score} points!"

See how much clearer the f-string is? You can instantly see what the final message will look like, and you don’t need to convert numbers to strings manually!

Expressions Inside F-Strings

Here’s where f-strings get really powerful: you can put any Python expression inside the curly braces, not just variables:

price = 19.99
quantity = 3

# You can do math directly inside!
print(f"Total cost: ${price * quantity}")  # Shows: Total cost: $59.97

# You can call methods!
name = "python"
print(f"Language: {name.upper()}")  # Shows: Language: PYTHON

# You can use conditions (we'll learn more about these later)
age = 15
print(f"Access: {'Granted' if age >= 13 else 'Denied'}")  # Shows: Access: Granted

Formatting Numbers

F-strings let you control how numbers are displayed. This is especially useful for decimals:

pi = 3.14159265359

# Show only 2 decimal places
print(f"Pi is approximately {pi:.2f}")  # Shows: Pi is approximately 3.14

# Show 4 decimal places
print(f"More precise: {pi:.4f}")  # Shows: More precise: 3.1416

# Add thousands separator
big_number = 1000000
print(f"One million: {big_number:,}")  # Shows: One million: 1,000,000

The :.2f means “format as a float with 2 decimal places.” The :, adds commas for readability.

Multi-Line F-Strings

You can use f-strings with triple quotes too:

name = "Sam"
level = 5
score = 1250

report = f"""
Player Report
=============
Name: {name}
Level: {level}
Score: {score}
"""

print(report)

This creates nicely formatted, multi-line output with all your variables filled in.


Quick Recap 🎯

Excellent progress! You’ve learned powerful text manipulation skills:

✅ Strings hold text inside quotation marks
✅ Concatenation (+) joins strings together
✅ Repetition (*) repeats strings
✅ String methods like .upper(), .lower(), .strip() transform text
✅ F-strings make combining text and variables easy and readable

Mastering strings opens up so many possibilities — from creating messages to processing user input!


🚀 Hands-On Exercise: Build a Character Profile Generator

Let’s create a fun program that generates a character profile for a game or story!

Your Mission:

  1. Create variables for a character:

    • character_name (a string)
    • character_class (like “Warrior”, “Mage”, “Rogue”)
    • level (a number)
    • health_points (a number)
    • magic_power (a number)
  2. Use string methods to:

    • Make the character name appear in ALL CAPS
    • Make the class appear in title case
  3. Use f-strings to create a formatted character card that displays:

    • The character’s name and class
    • Their stats (level, health, magic)
    • A special message about their total power (health + magic)
  4. Add some visual flair:

    • Use string repetition to create decorative borders
    • Format numbers nicely

Example Solution:

# Character Profile Generator

# Character information
character_name = "shadow blade"
character_class = "rogue"
level = 12
health_points = 85
magic_power = 45

# Format the name and class
formatted_name = character_name.upper()
formatted_class = character_class.title()

# Calculate total power
total_power = health_points + magic_power

# Create the character card
border = "=" * 40

character_card = f"""
{border}
           CHARACTER PROFILE
{border}

Name:   {formatted_name}
Class:  {formatted_class}
Level:  {level}

--- Stats ---
Health:       {health_points} HP
Magic Power:  {magic_power} MP
Total Power:  {total_power}

{border}
Status: {"LEGENDARY" if total_power > 100 else "COMMON"} Tier
{border}
"""

print(character_card)

Challenge Yourself:

  • Create profiles for multiple characters
  • Add a bio section using multi-line strings
  • Use .replace() to create a title from a character’s name (replace spaces with underscores)
  • Calculate and display percentage stats (like “75% health remaining”)
  • Add special characters or emojis to make it more visually interesting

Experiment! Try different formatting options, combine multiple methods, and make the profile your own style.


What’s Next? 🎮

In the next chapter, you’ll learn how to make your programs interactive by getting input from users! Your programs will finally be able to have conversations.


You’re becoming a text-formatting expert! Keep building!