Three Options
a, b = "hello", "world"
# 1. +
greeting = a + " " + b
# 2. f-string
greeting = f"{a} {b}"
# 3. join
greeting = " ".join([a, b])
Which to Use When
- f-strings ā most readable. Use by default.
- join ā combining many items from a list.
- + ā fine for two or three short strings.
Why NOT to Use + in a Loop
# Slow: O(n²) behaviour
result = ""
for word in words:
result += word
# Fast: O(n)
result = "".join(words)
Repeating a String
"-" * 20 # '--------------------'
Practise this on PyForm ā free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm ā