Strings, Numbers, and Dates
What You'll Learn
All the ways to create and manipulate strings and numbers, and how to work with dates and times using Python's standard library.
Strings In Depth
Creating Strings
single = 'Hello'
double = "World"
multiline = """Line 1
Line 2
Line 3"""
raw = r"C:\Users\alice\data" # raw string: backslashes are literal
String Indexing and Slicing
name = "Python"
# 012345 (positive indexes)
# -654321 (negative indexes)
print(name[0]) # P
print(name[-1]) # n
print(name[0:3]) # Pyt (start:stop, stop excluded)
print(name[::2]) # Pto (every 2nd character)
print(name[::-1]) # nohtyP (reversed)
Essential String Methods
text = " Hello, World! "
print(text.strip()) # "Hello, World!" (remove whitespace)
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
print(text.strip().split(", ")) # ['Hello', 'World!']
sentence = "the quick brown fox"
print(sentence.title()) # "The Quick Brown Fox"
print(sentence.count("o")) # 2
print(sentence.startswith("the")) # True
print(sentence.endswith("fox")) # True
print("quick" in sentence) # True
String Formatting
f-strings (best — use these):
name = "Alice"
score = 95.7
print(f"Player {name} scored {score:.1f}%")
# Player Alice scored 95.7%
# Expressions inside {}
print(f"Next year: {2024 + 1}")
# Next year: 2025
format() method (older style):
print("{} is {} years old".format("Alice", 30))
% formatting (very old — avoid):
print("%s is %d years old" % ("Alice", 30))
String Operations
# Concatenation
greeting = "Hello" + " " + "World"
# Repetition
line = "-" * 40
print(line) # ----------------------------------------
# Membership
print("ell" in "Hello") # True
print("xyz" not in "Hello") # True
# Length
print(len("Python")) # 6
Numbers In Depth
Integer Operations
x = 17
print(x + 3) # 20
print(x - 5) # 12
print(x * 4) # 68
print(x / 4) # 4.25 (always float)
print(x // 4) # 4 (floor division, integer result)
print(x % 4) # 1 (remainder/modulo)
print(x ** 2) # 289 (power)
Float Operations
import math
pi = 3.14159
print(round(pi, 2)) # 3.14
print(math.floor(pi)) # 3
print(math.ceil(pi)) # 4
print(math.sqrt(16)) # 4.0
print(abs(-42)) # 42
# Floating point caveat
print(0.1 + 0.2) # 0.30000000000000004
print(round(0.1 + 0.2, 1)) # 0.3 (use round() for display)
Useful Math Functions
import math
math.sqrt(25) # 5.0
math.pow(2, 8) # 256.0
math.log(100, 10) # 2.0
math.pi # 3.141592653589793
math.e # 2.718281828459045
min(3, 1, 4, 1, 5) # 1
max(3, 1, 4, 1, 5) # 5
sum([1, 2, 3, 4, 5]) # 15
Number Formatting for Display
price = 1234567.89
print(f"{price:,.2f}") # 1,234,567.89
print(f"{price:.0f}") # 1234568
print(f"{0.875:.1%}") # 87.5%
print(f"{255:08b}") # 11111111 (binary, 8 digits)
print(f"{255:x}") # ff (hex)
Dates and Times
from datetime import datetime, date, timedelta
# Current date and time
now = datetime.now()
print(now) # 2024-01-15 10:30:45.123456
# Just the date
today = date.today()
print(today) # 2024-01-15
# Create a specific date
birthday = date(1995, 8, 20)
print(birthday) # 1995-08-20
# Date arithmetic
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
in_90_days = today + timedelta(days=90)
# Age calculation
age = (today - birthday).days // 365
print(f"Age: {age} years")
Formatting Dates
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2024-01-15
print(now.strftime("%d/%m/%Y")) # 15/01/2024
print(now.strftime("%B %d, %Y")) # January 15, 2024
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2024-01-15 10:30:45
Parsing Date Strings
from datetime import datetime
date_str = "2024-01-15"
dt = datetime.strptime(date_str, "%Y-%m-%d")
print(dt.year, dt.month, dt.day) # 2024 1 15
Common strftime Codes
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2024 |
%m | Month (01–12) | 01 |
%d | Day (01–31) | 15 |
%H | Hour (00–23) | 10 |
%M | Minute (00–59) | 30 |
%S | Second (00–59) | 45 |
%B | Full month name | January |
%A | Full weekday name | Monday |
Common Mistakes
| Mistake | Fix |
|---|---|
"hello"[10] — index too large | Check len() first |
"age: " + 25 — str + int | Use f-string or str(25) |
| Comparing floats exactly | Use round() or math.isclose() |
Using %d format in strftime | %d is day, not integer — use f"{n}" for integers |
Quick Reference
# String
s.upper() / s.lower() / s.strip()
s.replace(old, new)
s.split(sep)
s.startswith(x) / s.endswith(x)
len(s)
f"{s}" f"{n:.2f}" f"{n:,}"
# Number
abs(n) / round(n, d) / min() / max() / sum()
n // d # floor division
n % d # modulo
n ** e # power
# Date
from datetime import datetime, date, timedelta
datetime.now()
date.today()
date.today() + timedelta(days=7)
dt.strftime("%Y-%m-%d")
datetime.strptime(s, "%Y-%m-%d")