Strings, numbers, and the formatting between them are the bread and butter of any analysis pipeline. Get fluent at f-strings, integer-vs-float arithmetic, and basic string methods, and you can move data around with confidence.
Strings — the basics
Strings can use single or double quotes interchangeably. Triple quotes (''' or """) allow multi-line strings. Strings are immutable: methods return new strings rather than modifying in place.
name = 'Kenya'name.upper() # 'KENYA' — returns a new stringname.lower() # 'kenya'name.replace('K', 'B') # 'Benya'len(name) # 5'Africa' in 'sub-Saharan Africa' # True
f-strings — the formatting tool you'll use most
Python 3.6+ introduced f-strings, which allow you to embed expressions inside string literals using curly braces. They are by far the cleanest formatting tool in the language.
rate = 0.1235print(f'The CBR is {rate:.2%}') # 'The CBR is 12.35%'print(f'KES {1234567:,.0f}') # 'KES 1,234,567'name, gdp = 'Kenya', 110_000print(f'{name}: ${gdp:,}M') # 'Kenya: $110,000M'
Integer vs float division
In Python 3, the / operator always returns a float, even for integer operands. Use // for integer (floor) division when you want an int result.
10 / 3 # 3.3333333333333335 (float)10 // 3 # 3 (int)10 % 3 # 1 (modulo)10 ** 3 # 1000 (exponentiation)
Numbers — three things to know
- Integer overflow doesn't exist in Python — ints grow as needed.
- Floats are IEEE 754, with the usual precision warnings: 0.1 + 0.2 == 0.3 is False because 0.1 has no exact binary representation.
- Use the decimal module for money or any context where 0.1 + 0.2 == 0.3 must be True.
Float comparison is dangerous
Never compare floats with ==. Use math.isclose(a, b) or abs(a - b) < tolerance. The 0.1 + 0.2 == 0.3 trap catches every junior analyst at least once.
Exercise
Given rate = 0.0875, format it as a percentage with two decimal places using an f-string.