Interview Questions: Strings Deep Dive
Strings come up in nearly every technical interview, from warm-up questions to full problems. This set goes deeper than earlier chapters — expect real interviewers to probe immutability, identity vs. equality, slicing edge cases, and the performance intuition behind string building.
1 Why are strings immutable in Python, and what does that mean in practice?
Once a string object is created, its contents can never be changed in place. Every string method that looks like it "modifies" a string — .upper(), .replace(), += — actually builds and returns a brand-new string object, leaving the original untouched. In practice this means you must always capture the result: s.upper() alone does nothing to s; you need s = s.upper() to rebind the variable to the new string.
Believing s[0] = "X" works, or writing s.strip() on its own line and expecting s itself to have changed.
"What actually happens when you run s = s.upper()?" (Expect: a new string object is created in memory; s is rebound to point at it; the old string object is unchanged and discarded once nothing references it anymore.)
2 Why can s1 == s2 and s1 is s2 give different answers for strings?
== compares values — are the two sequences of characters equal, character for character? is compares identity — are the two names pointing at the exact same object in memory (same id())? CPython sometimes reuses ("interns") short, simple string literals internally, so two equal literals can occasionally also be is-identical — but that's an implementation detail, never a guarantee. Value comparison should always use ==.
Using is to compare string contents "because it worked once" — identity checks on strings are fragile and shouldn't be relied on for equality.
"If s1 = "hello world" and s2 = "hello world", is s1 is s2 guaranteed to be True?" (No — interning behavior is a CPython implementation detail and shouldn't be depended on either way; only == is guaranteed to reflect value equality.)
3 What happens with out-of-range indices and negative steps in slicing?
Slicing never raises an error for out-of-range bounds — Python silently clamps them, so "hello"[10:20] just returns "" instead of crashing. Single-index access is different: "hello"[10] does raise IndexError. A negative step reverses the direction of travel: s[::-1] walks the whole string backward (a common way to reverse a string), and s[5:1:-1] walks backward from index 5 down to, but not including, index 1.
Assuming s[100] behaves like slicing and safely returns an empty result — single-index out-of-range access crashes, slicing never does.
"What does "hello"[10:20] return? What does "hello"[10] do?" ("" for the slice; IndexError for the single index.)
4 What's the difference between .find() and .index()?
Both search for a substring and return the lowest index where it starts. .find() returns -1 if the substring isn't found. .index() raises a ValueError instead. Use .find() when "not found" is a normal, expected outcome you'll handle with a plain if check; reach for .index() when a missing substring should be treated as an error condition.
Assuming the two are interchangeable, or assuming .find() raises an exception on failure.
"How would you safely check whether a substring exists, without risking a crash?" (Use the in operator, or check s.find(sub) != -1.)
5 Why does "5" + 5 raise a TypeError, but f"{5}" works fine?
Python's + operator doesn't auto-convert types between a string and an int — unlike some languages, it refuses to guess whether you meant arithmetic or concatenation, so it raises TypeError: can only concatenate str (not "int") to str. You have to convert explicitly, with str(5) or by dropping the value into an f-string: f"{5}" formats any value to its string representation automatically inside the braces, no explicit str() call needed.
Expecting Python to silently coerce an int to a string during +, the way looser-typed languages do.
"What's the fix for "Age: " + 25?" ("Age: " + str(25), or more idiomatically f"Age: {25}".)
6 How would you reverse a string in Python?
s[::-1] — a slice with no start or stop and a step of -1, walking the entire string backward in one expression. There's no .reverse() method on strings; that method belongs to mutable sequences (like lists, coming in Chapter 7) that can be rearranged in place — strings can't be, since they're immutable.
Trying to call a .reverse() method directly on a string.
"How would you check if a string is a palindrome?" (Compare s == s[::-1].)
7 Why is repeated += string concatenation inside a loop considered costly?
Because strings are immutable, every += inside a loop builds a brand-new string object and copies all the characters accumulated so far into it, then discards the old object. Across n iterations building a result of length n, that repeated re-copying can cost O(n²) time in the worst case, not O(n) — each step re-copies everything before it. The standard fix, once collections are available, is to gather the individual pieces separately and combine them once at the end with "".join(pieces), which is a single O(n) pass instead of many.
Treating string concatenation as "free," the way fixed-size numeric addition is, and not recognizing a growing += loop as a performance smell during code review.
"Why does joining pre-collected pieces avoid the repeated-copy problem that += has?" (Because the join happens once, after all pieces are known, instead of re-copying a growing string on every single iteration.)
8 What's a common gotcha with .strip()?
.strip() (and .lstrip()/.rstrip()) only removes characters from the very beginning and/or end of a string — it never touches anything in the middle, even if the same character shows up there too. By default it strips whitespace, but you can pass it a string of characters to remove instead; that argument is treated as a set of characters to strip from the ends, not a substring to remove as a single unit.
Expecting .strip() to clean up whitespace in the middle of a string, or expecting .strip("ab") to remove the two-character sequence "ab" rather than any mix of the individual characters 'a' and 'b' from the ends.
"What does "xxhixx".strip("x") return?" ("hi" — the leading and trailing 'x' characters are removed, stopping as soon as a non-'x' character is reached on each side.)
9 What's a pitfall with case-insensitive string comparison?
The usual approach is normalizing both sides the same way before comparing, e.g. s1.lower() == s2.lower(). The pitfall is normalizing only one side and forgetting the other — comparing s1.lower() == s2 will fail to match "CAT" against "cat" even though a human would call them equal, because s2 was never lowered.
Lowering (or uppercasing) just one operand and assuming the comparison is now case-insensitive.
Follow-up"How would you check if user input of 'YES', 'yes', or 'Yes' should all count as a yes?" (Lower the input once, e.g. answer.lower() == "yes".)
10 What's the difference between .split() with no arguments and .split(",") with a specific separator?
.split() with no arguments splits on any run of whitespace, collapses consecutive whitespace into a single split point, and discards leading/trailing whitespace entirely — " a b ".split() gives two pieces. .split(",") with an explicit separator splits on that exact character(s) and does not collapse repeats: "a,,b".split(",") gives three pieces, including an empty string between the two commas.
Assuming an explicit separator behaves like the no-argument form and silently drops empty pieces between repeated separators.
Follow-up"What does "a,,b".split(",") return, and how many elements does it have?" (Three pieces: the text before the first comma, an empty string between the two commas, and the text after — because an explicit separator never collapses repeats.)
11 How do you safely check if a string is a number before converting it?
The pattern taught so far is checking s.isdigit() before calling int(s), so you avoid handing int() something it can't parse. But .isdigit() has real limits: it returns False for a leading minus sign or a decimal point, so both "-5".isdigit() and "3.14".isdigit() are False even though both look like numbers to a human. Once exception handling is introduced in a later chapter, the more robust approach is to just attempt the conversion inside a try/except and handle failure directly, rather than trying to out-guess every valid numeric format up front.
Assuming .isdigit() correctly validates negative numbers or decimals — it only recognizes plain digit characters.
"Why doesn't "-5".isdigit() return True?" (Because '-' isn't a digit character, and .isdigit() requires every character in the string to be a digit, with no allowance for a sign or a decimal point.)
12 What's the difference between .isalnum() and checking .isalpha() or .isdigit()?
.isalnum() returns True when every character in the string is either a letter or a digit (and the string isn't empty) — so it accepts genuinely mixed strings like "abc123". .isalpha() alone requires every character to be a letter (fails on "abc123" because of the digits), and .isdigit() alone requires every character to be a digit (also fails on "abc123"). So .isalpha() or .isdigit() only returns True for a string that is purely letters or purely digits — never for a genuine mix of both. The two checks are not interchangeable.
Treating .isalnum() as shorthand for .isalpha() or .isdigit() — it's a materially broader check.
"What does "abc123".isalnum() return? What does "abc123".isalpha() or "abc123".isdigit() return?" (True; then False.)
13 What's the practical difference between a mutable and an immutable sequence, using a string as the example?
An immutable sequence, like a string, can't have any of its elements changed, added, or removed after creation — s[0] = "X" raises a TypeError. Any "change" has to build and assign a whole new string. A mutable sequence (like a list, in Chapter 7) can have individual elements changed in place, e.g. my_list[0] = "X" works fine, without creating a new object. This matters because immutability guarantees a string can't be silently altered elsewhere in a program while you're holding a reference to it — but it also means any "edit in place" idea (removing one character, swapping one letter) requires rebuilding a new string rather than mutating the original directly.
Writing s[0] = "X" and being surprised by the error, without understanding why it fails — it's not a syntax rule, it's a direct consequence of strings being immutable.
"How would you change just the first character of a string to uppercase, using only what's been taught so far?" (Rebuild it: s[0].upper() + s[1:] — concatenate a new first character with the rest of the original string via slicing.)
14 Why prefer .startswith()/.endswith() over slicing or .find() for a prefix/suffix check?
.startswith(sub)/.endswith(sub) say exactly what you mean and handle length differences safely without you computing slice indices yourself. Using slicing (s[:len(sub)] == sub) works but requires getting the length arithmetic right, which is easy to get subtly wrong. Using .find(sub) == 0 as a prefix check technically works too, but it's solving a bigger problem than necessary — .find() searches the entire string for the first occurrence anywhere, not just at the start.
Reaching for .find() or manual slicing when .startswith()/.endswith() says exactly what's intended and doesn't need to scan the whole string.
"How would you check if a filename ends in .txt?" (filename.endswith(".txt").)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.