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 โ