01.3 - Input/Output & String Formatting
Console Output: print()
The print() function writes to standard output (the terminal).
print("Hello, World!")
print(42)
print(3.14, "hello", True) # multiple arguments
# Separator (default is space)
print("a", "b", "c", sep="-") # a-b-c
print("a", "b", "c", sep="") # abc
# End character (default is newline \n)
print("Loading", end="...")
print("Done") # Loading...Done (on same line)
# Print to stderr
import sys
print("Error!", file=sys.stderr)
Console Input: input()
input() pauses execution, shows a prompt, and returns the user's input as a string.
name = input("Enter your name: ") # always returns str
age = int(input("Enter your age: ")) # convert to int
price = float(input("Price: ")) # convert to float
# Validation pattern
while True:
user_input = input("Enter a positive number: ")
if user_input.isdigit() and int(user_input) > 0:
number = int(user_input)
break
print("Invalid input, try again.")
String Formatting — 3 Methods
Python has three ways to format strings. Always prefer f-strings (Python 3.6+).
Method 1 — f-strings (Recommended)
name = "Alice"
age = 30
height = 1.75
# Basic substitution
greeting = f"Hello, {name}! You are {age} years old."
# Expressions inside {}
f"Next year you'll be {age + 1}"
f"Height in cm: {height * 100:.0f}"
# Format specifiers
pi = 3.14159265
f"{pi:.2f}" # "3.14" — 2 decimal places
f"{pi:.4f}" # "3.1416" — 4 decimal places
f"{1234567:,}" # "1,234,567" — thousands separator
f"{0.1756:.1%}" # "17.6%" — percentage
f"{'hello':>10}" # " hello" — right-align in 10 chars
f"{'hello':<10}" # "hello " — left-align
f"{'hello':^10}" # " hello " — center
f"{42:05d}" # "00042" — zero-padded integer
Method 2 — .format() (Legacy, still common)
"Hello, {}! You are {}.".format("Alice", 30)
"Hello, {name}!".format(name="Alice")
"{0} and {1} and {0}".format("spam", "eggs") # spam and eggs and spam
"{:.2f}".format(3.14159) # "3.14"
Method 3 — % Formatting (Very old, avoid)
"Hello, %s! Age: %d" % ("Alice", 30) # "Hello, Alice! Age: 30"
"Pi is %.2f" % 3.14159 # "Pi is 3.14"
f-string Format Specifiers Cheat Sheet
f"{value:[fill][align][sign][width][grouping][.precision][type]}"
| Specifier | Meaning | Example | Output |
|---|---|---|---|
d | Integer | f"{42:d}" | "42" |
f | Float | f"{3.14:.2f}" | "3.14" |
e | Scientific | f"{12345:.2e}" | "1.23e+04" |
% | Percentage | f"{0.85:.1%}" | "85.0%" |
s | String | f"{'hi':s}" | "hi" |
x | Hex | f"{255:x}" | "ff" |
b | Binary | f"{10:b}" | "1010" |
> | Right align | f"{'hi':>8}" | " hi" |
< | Left align | f"{'hi':<8}" | "hi " |
^ | Center | f"{'hi':^8}" | " hi " |
0 | Zero-pad | f"{7:03d}" | "007" |
, | Thousands | f"{1000000:,}" | "1,000,000" |
String Slicing
Strings are sequences — you can extract substrings with slices.
s = "Python Programming"
# 0123456789...
s[0] # 'P'
s[-1] # 'g' (last character)
s[0:6] # 'Python' [start:stop] — stop is exclusive
s[7:] # 'Programming' — from index 7 to end
s[:6] # 'Python' — from start to index 6
s[::2] # 'Pto rgamn' — every 2nd character
s[::-1] # reverse string!
# Common patterns
filename = "report_2024.csv"
extension = filename[-3:] # "csv"
basename = filename[:-4] # "report_2024"
Essential String Methods
text = " Hello, World! "
# Cleaning
text.strip() # "Hello, World!" — remove whitespace
text.lstrip() # "Hello, World! " — left only
text.rstrip() # " Hello, World!" — right only
# Case
"hello".upper() # "HELLO"
"HELLO".lower() # "hello"
"hello world".title() # "Hello World"
"Hello World".swapcase() # "hELLO wORLD"
# Search
"hello".find("ll") # 2 (first occurrence index)
"hello".count("l") # 2 (number of occurrences)
"hello".startswith("he") # True
"hello".endswith("lo") # True
# Split and join
"a,b,c".split(",") # ["a", "b", "c"]
"hello world".split() # ["hello", "world"] — splits on whitespace
",".join(["a", "b", "c"]) # "a,b,c"
"\n".join(["line1", "line2"]) # "line1\nline2"
# Replace
"cat sat on a mat".replace("at", "og") # "cog sog on a mog"
# Check content
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # True
Multi-line Strings and Raw Strings
# Multi-line string (triple quotes)
sql = """
SELECT name, age
FROM users
WHERE age > 18
ORDER BY name;
"""
# Raw strings — backslashes are literal
path = r"C:\Users\alice\Documents" # no need to escape \
regex = r"\d+\.\d+" # regex pattern
# Regular string — must escape backslashes
path2 = "C:\\Users\\alice\\Documents"
newline = "Line 1\nLine 2"
tab = "Col1\tCol2"
String Immutability
Strings in Python are immutable — you cannot change them in place.
s = "hello"
# s[0] = "H" # TypeError: 'str' object does not support item assignment
# You must create a new string
s = "H" + s[1:] # "Hello"
# Why does this matter?
s = "hello"
s = s.upper() # Creates a NEW string "HELLO", s now points to it
repr() vs str()
# str() — human-readable
str(3.14) # "3.14"
str(None) # "None"
# repr() — unambiguous, for debugging
repr("hello") # "'hello'" (includes quotes)
repr(None) # "None"
repr([1,2,3]) # "[1, 2, 3]"
# In f-strings: use !r for repr
name = "Alice"
f"{name}" # Alice
f"{name!r}" # 'Alice' (with quotes — useful for debugging)
Key Vocabulary
| Term | Definition |
|---|---|
| f-string | Formatted string literal with f"..." — the modern way to embed variables |
| Format specifier | Code after : in {value:spec} controlling alignment, precision, type |
| Slice | s[start:stop:step] — extract a substring |
| Immutable | Cannot be modified after creation; operations always return new strings |
str() | Converts an object to its human-readable string representation |
repr() | Converts an object to its unambiguous developer representation |
| Raw string | r"..." — backslashes are treated as literal characters |
strip() | Removes leading and trailing whitespace (or specified characters) |
Summary
print()supportssepandendparameters for formatting outputinput()always returns a string — always convert explicitly- f-strings are the modern, readable way to format strings:
f"Hello, {name}!" - Format specifiers control alignment (
<>^), width, precision (.2f), and type (d,f,%) - Strings are immutable — all methods return new strings
- Slicing
s[start:stop:step]extracts substrings without modifying the original
📄️ 01.1 - Variables & Data Types
Master Python's built-in types: int, float, str, bool, None — and understand how variables work in a dynamically typed language
📄️ 01.2 - Operators & Expressions
Master Python's arithmetic, comparison, logical, bitwise, and assignment operators with operator precedence rules
📄️ 01.3 - Strings & I/O
Master Python string formatting (f-strings, format(), %), console I/O with input()/print(), and essential string operations
📄️ Lab - Module 01
Build an interactive command-line calculator using variables, operators, type conversion, and f-string formatting
📄️ Quiz - Module 01
30 interactive questions covering variables, data types, operators, and string formatting