Introduction to Python: Output and String Manipulation

SA
StudyAI Editorial
Reviewed by StudyAI tutors
· Published Updated

From the foundation of computing curriculum

Introduction to Python: Output and String Manipulation

TL;DR

You'll learn how to display information to the user in Python using the print() function. We'll also cover how to combine and change text, called strings, for useful output. Understanding these basics lets you communicate results and interact with your programs.

1. The Mental Model

Think of your Python program as a chef in a kitchen. Output is like the chef serving a dish to a customer, showing them what's been prepared. String manipulation is like the chef taking raw ingredients (individual words or letters) and combining or modifying them to create a full, tasty meal.

2. The Core Material

2.1 Displaying Output with print()

Black and white abstract blocks on a white background, conceptual design.
Photo by Google DeepMind on Pexels

The most basic way to show something in Python is with the print() function. You put whatever you want to display inside its parentheses.

print("Hello, world!")
print(123)
print(3.14159)

This will display:

Hello, world!
123
3.14159

Notice how print() automatically adds a new line after each item. You can print multiple items at once, separated by commas, and print() will put a space between them.

name = "Alice"
age = 30
print("My name is", name, "and I am", age, "years old.")

Output:

My name is Alice and I am 30 years old.

2.2 What Are Strings?

Detailed view of a violin fingerboard showcasing strings and intricate craftsmanship.
Photo by Diana ✨ on Pexels

A string is just a sequence of characters (letters, numbers, symbols, spaces) enclosed in quotes. You can use single quotes (') or double quotes ("). It doesn't matter which you use, as long as you're consistent.

greeting = "Hello"
question = 'How are you?'

2.3 Combining Strings (Concatenation)

Close-up of soft blue and green yarn balls, perfect for knitting and crochet projects.
Photo by Valentin Ivantsov on Pexels

You can join strings together using the + operator. This is called concatenation.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

Output:

John Doe

Remember to add spaces yourself if you want them between words.

2.4 Repeating Strings

Close-up image of a child playing the violin indoors, focusing on the strings and hand.
Photo by MART PRODUCTION on Pexels

You can repeat a string multiple times using the * operator with an integer.

separator = "=" * 20
print(separator)
print("Menu")
print(separator)

Output:

====================
Menu
====================

2.5 F-Strings (Formatted String Literals)

F-strings are a powerful and easy way to embed variables directly into strings. You prefix the string with an f (or F) and place variables inside curly braces {}.

item = "Laptop"
price = 1200
message = f"The {item} costs ${price:.2f}." # :.2f formats to 2 decimal places
print(message)

Output:

The Laptop costs $1200.00.

2.6 String Manipulation Process

Here's a look at how you often combine these ideas to prepare data for output.

graph TD
    A["Start with raw data (variables)"] --> B["Convert data to strings (if needed)"];
    B --> C["Combine strings (concatenation, f-strings)"];
    C --> D["Add formatting (spaces, newlines, specific variable formatting)"];
    D --> E["Display output using print()"];
    E --> F["End"];

3. Worked Example

Let's say you're building a simple program to calculate a total bill with tax.

item1_name = "Keyboard"
item1_price = 75.50

item2_name = "Mouse"
item2_price = 25.00

tax_rate = 0.08  # 8%

# Calculate subtotal
subtotal = item1_price + item2_price

# Calculate tax
tax_amount = subtotal * tax_rate

# Calculate total
total_bill = subtotal + tax_amount

# Prepare output using f-strings for clear formatting
print("--- Receipt ---")
print(f"Item: {item1_name:<10} Price: ${item1_price: >7.2f}") # <10 left aligns in 10 chars, >7.2f right aligns in 7 chars with 2 decimals
print(f"Item: {item2_name:<10} Price: ${item2_price: >7.2f}")
print("-" * 25)
print(f"Subtotal:       ${subtotal: >7.2f}")
print(f"Tax ({tax_rate:.0%}):    ${tax_amount: >7.2f}") # .0% formats as percentage with no decimals
print("-" * 25)
print(f"Total:          ${total_bill: >7.2f}")
print("---------------")

Output:

--- Receipt ---
Item: Keyboard   Price: $  75.50
Item: Mouse      Price: $  25.00
-------------------------
Subtotal:       $ 100.50
Tax (8%):       $   8.04
-------------------------
Total:          $ 108.54
---------------

4. Key Takeaways

  • The print() function is your primary tool for displaying information to the user.
  • Strings are sequences of characters enclosed in single or double quotes.
  • Use the + operator to combine strings (concatenation).
  • Use the * operator with an integer to repeat a string.
  • F-strings (e.g., f"Text {variable}") are the modern and most readable way to embed variables and expressions into strings.
  • You can apply formatting inside f-strings to control alignment, decimal places, and more.

Common Mistakes to Avoid:

  • Forgetting quotes around string literals when printing or assigning.
  • Trying to directly concatenate a number and a string with + without converting the number to a string first (f-strings handle this automatically).
  • Expecting print() to automatically add spaces between items when concatenating with + (it only does this when items are separated by commas within the print() function itself).
  • Not understanding that print() adds a newline by default.

5. Now Try It

Create a small program that takes your favorite animal and its typical lifespan in years. Then, use print() and f-strings to display a sentence like: "My favorite animal is the [Animal Name], and it typically lives for [Lifespan] years." Make sure to include a second line that says "That's quite a long time!" if the lifespan is over 10 years, or "That's a bit short!" otherwise.

What success looks like: Your program will ask for an animal and its lifespan, then print a well-formatted output message that correctly adjusts based on the lifespan you enter.

Frequently asked about Introduction to Python: Output and String Manipulation

You'll learn how to display information to the user in Python using the print() function. We'll also cover how to combine and change text, called strings, for useful output. Understanding these basics lets you communicate results and interact with your programs. Read the full notes above for the details.

Introduction to Python: Output and String Manipulation is a core topic in foundation of computing. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.

Study this next


Get the full foundation of computing curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Create Free Account