Predict the output · Python
Strings and immutability
String operations, joining with numbers, and comparisons.
Learn: Predicting what Python string code prints7 minute read
A "predict the output" question shows a short script and asks what it prints. Python string questions are common in tester interviews because test code handles text all the time: page titles, log lines, API fields and CSV rows. They test a few rules again and again: strings never change, slices are forgiving, and Python never mixes text and numbers on its own. Once these rules are clear, most string questions become a short trace.
Rule 1: strings are immutable
Immutable means the string cannot change after it is created. Methods such as upper(), replace() and strip() return a new string; they never change the original. A call on its own line, with nothing storing the result, has no visible effect. Even s += "x" builds a new string and points s at it; any other name that referred to the old string still sees the old text. Assigning to one position, s[0] = "b", raises a TypeError, an error that stops the program.
Rule 2: + joins only strings, * repeats
With two strings, + joins them. With a string and a number, it raises a TypeError, because Python never turns a number into text by itself. Use str() or an f-string, which is a string with f before the quotes that puts values inside curly brackets, such as f"n={5}". A string times a whole number repeats it, so "ab" * 2 is "abab", and times zero gives the empty string.
Rule 3: slices stop before the end and never fail
Indexes start at 0, and negative indexes count from the end, so s[-1] is the last character. A slice s[start:stop:step] includes start and stops before stop. s[-2:] is the last two characters, and a step of -1 walks backwards, which reverses the string. Out-of-range slice bounds are cut back to the length of the string instead of raising an error, so s[10:20] on a short string is just "". A single index, such as s[10], does raise IndexError, the error for an index that is out of range.
s = "login"
s.upper()
print(s)
print(s[1:3], s[-2:], s[::-1])
print(s[10:20] == "")
print("ab" + "cd", "ab" * 2)
login og in nigol True abcd abab
Rule 4: split() and split(" ") are different
With no argument, split() splits on any run of whitespace (spaces, tabs and new lines) and ignores spaces at both ends. With an argument, every single occurrence is a separator, so two separators next to each other produce an empty string between them, and a separator at either end produces an empty string there too.
Rule 5: strings compare by character codes
Comparison goes character by character, using each character's code point, its number in Unicode. All capital letters come before all lower-case letters, so "Z" < "a" is true. Digits in a string are characters too, so "10" < "9" is true because "1" comes before "9". Convert to int when you mean numbers.
line = " a b "
print(line.split())
print(line.split(" "))
print("Z" < "a", "10" < "9")
['a', 'b'] ['', 'a', '', 'b', ''] True True
Rule 6: searching and formatting
find returns the first index of a piece of text and rfind the last; both return -1 when it is missing. in checks for a run of characters next to each other. In an f-string, the part after a colon formats the value: .2f gives two decimals, 03d pads a whole number with zeros, and >4 right-aligns in four characters.
x = 3.14159
print(f"{x:.2f}|{7:03d}|{'ab':>4}|")
s = "hello world"
print(s.find("o"), s.rfind("o"), s.find("z"), "lo w" in s)
3.14|007| ab| 4 7 -1 True
Rule 7: compare text with ==, not is
== compares the characters. is asks whether two names point at the same object, and whether two equal strings are the same object depends on how they were created and on details of the interpreter (the program that runs your Python code). If an interview snippet uses is on strings, the honest answer is that you should not rely on it.
How to answer in an interview
Give the output, then the rule. "It prints login, because upper() returns a new string and the result was not stored." For slices, write the indexes under the word and count; say them out loud so the interviewer can follow. Finish with what you would do in real code, such as using split() without an argument for user input.
Common mistakes
- Thinking
s.upper()changess. - Expecting
"Total: " + 5to work as it does in Java. - Including the stop index of a slice.
- Expecting
s[10:20]to raise an error. - Comparing number-like strings and expecting numeric order.
Recap
Strings never change, so store what string methods return. + joins only strings and * repeats. Slices stop before the end and clip out-of-range bounds, while single indexes raise. split() without an argument handles runs of whitespace. Strings compare by code point, and text should be compared with ==. Printing a list of strings shows quotes around each item, because a list prints its items with repr(), the form meant for programmers, which shows quotes around text.
10 questions0/10 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | A string method whose result is not kept | Easy | |
| Not started | Slicing a string | Easy | Asked in: Infosys, PhonePe, Wipro |
| Pro+ | + and * with strings and numbers | Easy-Medium | |
| Pro+ | Joining a string and a number | Easy-Medium | |
| Pro+ | Changing one character of a string | Medium | |
| Pro+ | split() versus split(" ") | Medium | |
| Pro+ | Comparing and sorting strings | Medium | |
| Pro+ | count, find, rfind and replace with a limit | Medium | |
| Pro+ | f-string format specifiers | Medium | |
| Pro+ | Slices past the end and the in operator | Medium-Hard |
The first 2 questions of each topic are free. Pro+ opens every question.