Python string questions look easy until two answer options differ only by spaces. One asks whether .strip() changed the original object. Another hides three leading spaces inside a format width.
Both test the same skill: know exactly what an expression returns, and do not mentally change a string that Python left untouched.
Python strings are immutable
A string object cannot be changed after creation. Methods such as strip, replace, upper and lower return new strings. They do not edit the original object in place.
s = " Hello "
t = s.strip()After these lines, t is "Hello", while s is still " Hello ". Calling s.strip() without storing or using the returned value leaves s unchanged.
The same rule explains this trap:
s = "banana"
s.replace("a", "o")
print(s)The output is banana, not bonono. To keep the change, write s = s.replace("a", "o").
Immutability does not mean Python modifies a string secretly and copies it later. It means an operation that appears to change text produces another object. Once that rule is firm, many output questions collapse into simple assignment tracing.
Slicing strings precisely
The general slice is u[start:stop:step]. The start is included and the stop is excluded, so the selected index range is half-open.
For u = "abcdef":
u[1:4] # "bcd"
u[-2:] # "ef"
u[::-1] # "fedcba"
u[:3] # "abc"The first slice takes indices 1, 2 and 3. It stops before index 4. Negative indices count back from the end, so -1 identifies "f" and -2 identifies "e". Omitting both bounds with a step of -1 traverses the full string backwards.
Slicing and indexing behave differently at the boundary. u[20] raises IndexError, but u[:20] safely clamps the stop to the string's length and returns "abcdef".
Count the positions to confirm. Indices 1, 2 and 3 hold b, c and d, hence "bcd". Reversing the six positions 5, 4, 3, 2, 1, 0 gives f, e, d, c, b and a, hence "fedcba".
![Index box diagram of the string abcdef with positive and negative indices, showing the slices u[1:4], u[-2:] and u[::-1].](https://kgai.blob.core.windows.net/blog-assets/blog_asset_1784093696072_251svm.jpg)
For a larger set of these traces, Python Output-Based Questions connects slicing with list mutability and aliasing.
The workhorse string methods
split breaks one string into parts, while join combines an iterable of strings using a separator:
"a,b,c".split(",") # ["a", "b", "c"]
"-".join(["a", "b", "c"]) # "a-b-c"Remember that join belongs to the separator. Read the second line as, "join these parts using a hyphen."
Bare split() treats any run of whitespace as a separator and drops empty pieces at the ends. By contrast, split(" ") uses one literal space as the separator, so repeated spaces can create empty strings.
" a b ".split() # ["a", "b"]
"a b".split(" ") # ["a", "", "b"]The empty string in the second result is the gap between the two literal spaces. Bare split() never produces it.
Other methods worth separating clearly are:
Method | Result or behaviour |
|---|---|
| Return a copy with characters removed from both ends, the left end or the right end (whitespace by default) |
| Return a new string with replacements |
| Return the first index, or |
| Return the first index, or raise |
| Return a Boolean |
| Count non-overlapping occurrences |
| Return case-converted strings |
The distinction between find and index is a regular interview trap because both return the same answer when the substring exists. Only the missing case separates them.
String formatting three ways
F-strings are the modern default because the expression and its format sit together:
name = "Asha"
score = 91.5
result = f"{name} scored {score:.1f}"result is "Asha scored 91.5". The .1f requests fixed-point formatting with one digit after the decimal.
Now inspect width and alignment:
f"{score:>8.2f}"First, .2f turns 91.5 into "91.50", which has five characters. The total width is 8 and > means right-align. Python therefore adds 8 - 5 = 3 leading spaces, producing " 91.50".
Count them: three spaces plus five numeric characters is eight in total. That exact spacing is often the whole question.
The equivalent styles are:
"{} scored {:.1f}".format(name, score)
"%s scored %.1f" % (name, score)They remain valid, but f-strings are normally clearer. Whichever syntax appears, decode precision, type, width and alignment rather than guessing from appearance.
The repeated += performance trap
This loop appears harmless:
result = ""
for ch in chars:
result += chBecause strings are immutable, each apparent append may require a new string containing the old text plus the new character. Across growing lengths, the worst-case work is quadratic, O(n^2). Some Python implementations optimise particular cases, but interview reasoning should not depend on that optimisation.
When all parts are available, use:
result = "".join(chars)join can plan the final allocation and process the characters in linear O(n) time. The choice matters most when the number or total size of pieces grows.
Traps and interview question patterns
Do not use is to compare string values. == compares values, while is checks whether two references identify the same object. Interning can make a mistaken is comparison appear to work in one run and fail in another.
Also remember that case and whitespace are data. "Yes" == "yes " is false. ord('A') returns 65, while chr(65) returns 'A'. One maps a character to its integer code point and the other maps back.
Three question shapes recur. The first hands you a snippet and asks for the exact printed value:
raw = " Anita Rao "
raw.strip()
print(len(raw), len(raw.strip()))
print(raw.strip().replace(" ", "_"))
print(raw.find("Anita"), raw.strip().find("Anita"))The three printed lines are 13 9, then Anita_Rao, then 2 0. Line 2 changes nothing, because its returned value is discarded, so raw keeps its two leading and two trailing spaces and its length stays 13. The stripped copy is 9 characters, and replace turns its one interior space into an underscore. find reports index 2 on the padded string and index 0 on the stripped one, which is the trap: removing the padding shifts every index.
The second shape asks which comparison is safe, and the answer is == every time, never is. The third asks you to count characters inside a formatted field, where {:>8.2f} applied to 91.5 puts exactly three spaces before 91.50. All three are settled by tracking what an expression returns rather than imagining that a method edited the string.
KnowledgeGate's Python question bank holds over 450 questions, including more than 100 on collections and strings. That set covers immutability, split, join, strip and f-string details where exact return values matter.
The short version and next step
Strings never change in place, so capture the returned value. Slices are half-open, [::-1] reverses, join is the dependable builder for many pieces, and {:>8.2f} fixes both precision and spacing.
Use the Python Programming course for the complete strings module, and DSA Using Python when you want the same rules applied to coding-round problems. The Coding and DSA courses for placements page is the wider route when you are combining Python fundamentals with interview preparation.




