Python string MCQ questions with answers
Indexing, slicing, methods and formatting: predict the output, then check.
0 of 20 answered
Question 1 · Easy
What is the output of this code?
s = "PYTHON" print(s[0], s[-1], s[2])
Show the answer
Answer: B
Indexes start at 0, so
Run this code in the editors[0]isPands[2]isT. Negative indexes count from the end, ands[-1]is the last character,N.Question 2 · Easy
What is the output of this code?
s = "Programming" print(s[3:7])
Show the answer
Answer: C
A slice
Run this code in the editors[start:stop]includes the start index and stops before the stop index, sos[3:7]takes indexes 3, 4, 5 and 6:g,r,a,m.Question 3 · Easy
What is the output of this code?
s = "computer" print(s[-3:], s[:-3])
Show the answer
Answer: A
Run this code in the editors[-3:]starts three characters from the end and runs to the end, givingter.s[:-3]runs from the start up to, but not including, that same position, givingcompu.Question 4 · Medium
What is the output of this code?
s = "abcdefgh" print(s[::2], s[1::3])
Show the answer
Answer: D
The third number in a slice is the step.
Run this code in the editors[::2]takes every second character from index 0 (aceg), ands[1::3]takes indexes 1, 4 and 7 (beh).Question 5 · Hard
What is the output of this code?
s = "PYTHON" print(s[-2:-5:-1])
Show the answer
Answer: C
With a step of -1 the slice walks backwards from
Run this code in the editors[-2](O) and stops befores[-5](Y), so it takesO,H,T. The stop index is never included, ands[-1]is not the start here.Question 6 · Medium
What is the output of this code?
name = "python" name.upper() print(name)
Show the answer
Answer: D
Strings are immutable, so
Run this code in the editorupper()returns a new string instead of changingname. The result is thrown away because it is not assigned;name = name.upper()would keep it.Question 7 · Hard
What is the output of this code?
line = "red green" print(line.split()) print(line.split(" "))
Show the answer
Answer: B
With no argument,
Run this code in the editorsplit()splits on any run of whitespace, so the double space acts as one separator.split(" ")splits at every single space, so the two spaces leave an empty string between them.Question 8 · Easy
What is the output of this code?
letters = ["a", "b", "c"] print("-".join(letters)) print("".join(letters).upper())
Show the answer
Answer: A
Run this code in the editor"-".join(letters)puts the separator only between the items, not at the ends."".join(letters)givesabc, andupper()turns it intoABC.Question 9 · Medium
What is the output of this code?
s = "banana" print(s.find("an"), s.count("an"), s.find("x"))
Show the answer
Answer: D
Run this code in the editorfind()returns the index of the first match, andanfirst appears at index 1.count()counts non-overlapping matches (2). When there is no match,find()returns -1 rather than raising an error.Question 10 · Medium
What is the output of this code?
s = "a-b-c-d" print(s.replace("-", "+", 2)) print(s)
Show the answer
Answer: C
The third argument of
Run this code in the editorreplace()limits how many replacements are made, starting from the left, so only the first two-change.replace()returns a new string, sositself is unchanged.Question 11 · Hard
What is the output of this code?
print("apple" < "Banana", "10" < "9")
Show the answer
Answer: A
Strings compare character by character using Unicode code points. Uppercase letters come before lowercase ones (
Run this code in the editorBis 66,ais 97), so"apple" < "Banana"isFalse."10" < "9"compares1with9first, so it isTrue.Question 12 · Medium
What is the output of this code?
raw = " ab-2024 " code = raw.strip().upper() print(code) print(code.startswith("AB"), "2024" in code, code.isdigit())
Show the answer
Answer: D
Run this code in the editorstrip()removes the outer spaces andupper()givesAB-2024. It starts withABand contains2024, butisdigit()isFalsebecause the string also has letters and a hyphen.Question 13 · Easy
Which error does this code raise?
word = "cat" word[0] = "b" print(word)
Show the answer
Answer: B, TypeError: 'str' object does not support item assignment
Strings are immutable, so you cannot assign to one of their characters. Build a new string instead, for example
Run this code in the editorword = "b" + word[1:].Question 14 · Medium
Which error does this code raise?
numbers = [1, 2, 3] print("-".join(numbers))
Show the answer
Answer: A, TypeError: sequence item 0: expected str instance, int found
Run this code in the editorjoin()accepts only strings, and it does not convert numbers for you. Convert the items first:"-".join(str(n) for n in [1, 2, 3])gives1-2-3.Question 15 · Medium
Which error does this code raise?
s = "python" print(s[2:10]) print(s[10])
Show the answer
Answer: C, IndexError: string index out of range
A slice never raises an error:
Run this code in the editors[2:10]stops at the end of the string and printsthon. A single index must exist, sos[10]raisesIndexError.Question 16 · Easy
How many characters does the string
"a\nb"contain?Show the answer
Answer: C, 3
The escape sequence
\nis written with two symbols but stands for one character, a newline. So the string holdsa, a newline andb: three characters.Question 17 · Easy
What is the difference between
s.find(x)ands.index(x)whenxis not ins?Show the answer
Answer: A, find() returns -1 and index() raises ValueError
Both methods return the position of the first match. When there is no match,
find()returns -1, whileindex()raisesValueError: substring not found.Question 18 · Easy
For a non-empty string
s, which index refers to its last character?Show the answer
Answer: D, len(s) - 1
Indexes run from 0 to
len(s) - 1, and-1is a shortcut for that last position.s[len(s)]raisesIndexError, and-0is the same as 0, the first character.Question 19 · Medium
Which expression gives the string
sreversed?Show the answer
Answer: B
A slice with step -1 walks the whole string backwards and returns a new string. Strings have no
reverse()method,reversed(s)returns an iterator rather than a string, ands[-1:0:-1]stops before index 0, losing the first character.Question 20 · Hard
Given
value = 42.5, which line printsTotal: 42.50, with the number shown to two decimals and right-aligned in 8 characters?Show the answer
Answer: B
In
8.2f, 8 is the minimum width and.2fgives two decimals; numbers are right-aligned by default, so42.50gets three spaces in front.<would left-align it,.8fshows eight decimals, and8alone keeps42.5.
Keep going
- Read the lesson behind these questions: Strings in the PythonBook
- Next topic: Python if-else MCQ questions with answers
- Before this: Python operators MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.