Lesson 4 - Strings & Output Formatting
Learning Objective
Control print()’s output using sep and end, format values with f-strings, and perform basic string operations like concatenation, case conversion, and length.
Introduction
You’ve already used print() in every lesson so far, but it has more control than a single value dumped to the screen.
This lesson covers:
- Controlling what appears between printed values using
sep - Controlling what appears after printed values using
end - Formatting output with f-strings
- Comparing f-strings with older formatting approaches
- Performing common string operations such as concatenation, case conversion, and measuring string length
Understanding print()
The print() function can display one or more values.
Basic usage:
print("Hello, World!")Output:
Hello, World!You can also print multiple values at once:
print("Python", 3, "is awesome")Output:
Python 3 is awesomeCustomizing Output with sep and end
Controls what appears between multiple values.
print("a", "b", "c", sep=" - ")Output:
a - b - cControls what appears after the printed output.
print("Hello", end="!")Output:
Hello!Normally, print() ends with a newline (\n).
Code
# print_and_strings.py
name = "Rahul"
score = 91.5
# Basic print
print("Result ready.")
# Multiple values, custom separator and end
print("a", "b", "c", sep=" - ", end="!\n")
# f-strings (the modern, recommended approach)
print(f"{name} scored {score:.1f}%")
# .format() method (common in older codebases)
print("{} scored {:.1f}%".format(name, score))
# %-style formatting (legacy, still seen in older Python code)
print("%s scored %.1f%%" % (name, score))
# String operations
greeting = "Hello" + ", " + name + "!"
print(greeting.upper())
print(greeting.lower())
print(len(greeting))Expected Output
Click to see expected output
Result ready.
a - b - c!
Rahul scored 91.5%
Rahul scored 91.5%
Rahul scored 91.5%
HELLO, RAHUL!
hello, rahul!
13String Formatting with f-Strings
Modern Python code typically uses f-strings.
Example:
name = "Rahul"
score = 91.5
print(f"{name} scored {score:.1f}%")Output:
Rahul scored 91.5%The :.1f format specification means:
- Display as a floating-point number
- Show exactly 1 digit after the decimal point
Older Formatting Styles
Using .format()
print("{} scored {:.1f}%".format(name, score))Output:
Rahul scored 91.5%Using % Formatting
print("%s scored %.1f%%" % (name, score))Output:
Rahul scored 91.5%You’ll still encounter .format() and % formatting in older codebases, but f-strings are the preferred approach in modern Python.
Common String Operations
Concatenation
Joining strings together:
greeting = "Hello" + ", " + name + "!"Result:
Hello, Rahul!Convert to Uppercase
print(greeting.upper())Output:
HELLO, RAHUL!Convert to Lowercase
print(greeting.lower())Output:
hello, rahul!Find String Length
print(len(greeting))Output:
13Useful f-String Format Specifiers
price = 12.3456
print(f"{price:.2f}")Output:
12.35population = 1400000000
print(f"{population:,}")Output:
1,400,000,000price = 12345.678
print(f"${price:,.2f}")Output:
$12,345.68🔧 Under the Hood
How do f-strings actually work?
An f-string (f"...") is evaluated by the interpreter at runtime.
Anything inside {} is treated as a real Python expression, evaluated, converted to a string, and inserted into the final result.
For example:
f"{score:.1f}"The :.1f portion is a format specification that tells Python:
Render this value as a floating-point number with one decimal place.
Under the hood:
f"{name} scored {score:.1f}%"produces essentially the same result as:
"{} scored {:.1f}%".format(name, score)However, f-strings are generally more readable and often faster, which is why they are the recommended style in Python 3.6+.
String concatenation using + works only between strings:
"Score: " + "91.5"works, but:
"Score: " + 91.5raises a TypeError.
You would need:
"Score: " + str(91.5)which is one reason formatted strings are usually cleaner and easier to maintain.
Student Challenge
Reflection Question
This lesson showed three ways to build the same output string — f-strings,
.format(), and%formatting. If they all produce the same result, why does it still matter which one you reach for by default in your own code?
By the end of this lesson, you should be able to customize print() output, use f-strings confidently, understand older formatting styles, concatenate strings, change text case, and measure string length with len().