Chapter 06

Strings

Strings are immutable, indexable, iterable sequences. String interning creates surprising is results. f-strings have edge cases. Let's test you.

Questions: 16
Format: Predict Output + Multiple Choice
Difficulty: ★★★☆☆
Fundamental rule: Strings in Python are immutable. You can never modify a string in place. Every string operation returns a new string. This has big implications for performance when building strings in loops.
Immutability
Q 01Multiple Choice
s = "hello"
s[0] = "H"
Answer: b) TypeError.

Strings are immutable — you cannot change any character. TypeError: 'str' object does not support item assignment. To "modify" a string, you must create a new one: s = "H" + s[1:] or use s.replace("h", "H", 1).
Q 02Predict the Output
s = "hello"
s = s.upper()
print(s)
Output
HELLO
Why? .upper() returns a new string — it doesn't modify the original. The old "hello" string is abandoned and s is rebound to the new "HELLO" string. This is how all string methods work — they always return new strings.
String Interning
Q 03Predict the Output
a = "hello"
b = "hello"
print(a == b)
print(a is b)

c = "hello world"
d = "hello world"
print(c is d)   # may vary
Output (CPython typical)
True True False
Why? CPython interns short strings that look like identifiers (letters, digits, underscores). "hello" is interned — a is b is True. Strings with spaces like "hello world" may not be interned — c is d may be False. Never rely on string identity — always use ==.
String Operations
Q 04Predict the Output
print("abc" * 3)
print("-" * 20)
print("ab" * 0)
Output
abcabcabc --------------------
Why? String * integer = repetition. "abc" * 3 produces "abcabcabc". "-" * 20 creates a separator line. "ab" * 0 returns an empty string (not an error). Multiplying by a negative also gives empty string.
Q 05Multiple Choice
parts = ["a", "b", "c"]
result = ",".join(parts)
print(result)
print(type(result))
Answer: a) "a,b,c", str.

separator.join(iterable) joins the elements with the separator between each pair. It returns a single string. This is much more efficient than concatenation in a loop (s += item). Always use join() when building strings from a list.
Q 06Predict the Output
s = "  hello world  "
print(s.strip())
print(s.lstrip())
print(s.split())
print(s.split(" "))
Output
hello world hello world ['hello', 'world'] ['', '', 'hello', 'world', '', '']
Why? .strip() removes leading/trailing whitespace. .lstrip() only left side. .split() with no argument splits on ANY whitespace and discards empty strings — the smart default. .split(" ") splits on exact single space, preserving empty strings between consecutive spaces — rarely what you want.
f-strings
Q 07Predict the Output
name = "Alice"
score = 95.678
print(f"Hello, {name}!")
print(f"Score: {score:.2f}")
print(f"{2 ** 10}")   # expression in f-string
Output
Hello, Alice! Score: 95.68 1024
Why? f-strings evaluate expressions inside {} at runtime. :.2f is a format spec — 2 decimal places, rounded. 95.678 rounds to 95.68. Any valid Python expression can go inside the braces — including 2**10.
Q 08Multiple Choice
x = 42
print(f"{x=}")   # = inside f-string (Python 3.8+)
Answer: b) x=42.

The = specifier in an f-string (Python 3.8+) prints both the variable name and its value. f"{x=}" produces x=42. Extremely useful for debugging: print(f"{my_var=}") shows the variable name alongside its value without extra typing.
String Methods
Q 09Predict the Output
s = "hello"
print("e" in s)
print(s.startswith("he"))
print(s.endswith("LO"))
print(s.find("l"))
print(s.find("z"))
Output
True True False 2 -1
Why? in checks substring membership (case-sensitive). .startswith() and .endswith() are case-sensitive — "LO" ≠ "lo". .find() returns the index of the first occurrence, or -1 if not found (unlike .index() which raises ValueError if not found).
Q 10Predict the Output
s = "abcabc"
print(s.replace("a", "X"))
print(s.replace("a", "X", 1))
print(s)
Output
XbcXbc Xbcabc abcabc
Why? .replace(old, new) replaces ALL occurrences. .replace(old, new, count) replaces at most count occurrences. Crucially, the original string s is UNCHANGED — .replace() returns a new string. Never forget: strings are immutable.
Q 11Multiple Choice
s = "Python"
print(s[2:5])
print(s[-1])
print(s[::-1])
Answer: a) "tho", "n", "nohtyP".

"Python" indices: P=0, y=1, t=2, h=3, o=4, n=5. s[2:5] → "tho" (indices 2,3,4). s[-1] → "n" (last). s[::-1] reverses the string → "nohtyP". String slicing works exactly like list slicing.
String Formatting Quirks
Q 12Predict the Output
print("{}".format(42))
print("{0} {1} {0}".format("a", "b"))
print("{name}".format(name="Alice"))
Output
42 a b a Alice
Why? .format() is the older string formatting method (pre f-strings). {} = positional. {0}, {1} = index-based. {name} = keyword-based. Index-based allows reuse ({0} appears twice). f-strings are preferred in modern Python but .format() is still widely used.
Q 13Multiple Choice
result = ""
for i in range(5):
    result += str(i)
print(result)
Answer: a) "01234".

String concatenation with += in a loop works but is inefficient — each iteration creates a new string (since strings are immutable). For large loops, "".join(str(i) for i in range(5)) is much faster — it builds the string once. This is a classic performance pitfall.
Q 14Predict the Output
s = "hello"
print(list(s))
print(len(s))
for c in s:
    print(c, end="-")
Output
['h', 'e', 'l', 'l', 'o'] 5 h-e-l-l-o-
Why? Strings are iterable sequences of characters. list(s) converts to a list of individual characters. len(s) counts characters. A for loop iterates character by character. print(end="-") uses "-" as the line terminator instead of newline.
Q 15Multiple Choice
s = "  hello  "
print(s.strip() == "hello")
print(s.strip("h elo"))
Answer: a) True, "".

.strip() with no args strips whitespace. .strip("h elo") strips any characters in the given set from both ends — not the substring "h elo". The set is {h, space, e, l, o}. All characters in " hello " are in that set, so everything is stripped → "".
Q 16Predict the Output
s = "hello"
print(s.center(11))
print(s.center(11, "*"))
print(s.ljust(10, "."))
print(s.rjust(10, "."))
Output
hello ***hello*** hello..... .....hello
Why? .center(width, fill) centers the string in a field of given width, padding with the fill character. .ljust() left-justifies (pads right). .rjust() right-justifies (pads left). These are useful for formatting tabular output. Default fill is a space.
← Chapter 05: Lists & Slicing Chapter 07: Tuples →