Python Practice Test: Strings and Files
- String Methods and Reading Files
- 10 questions
- 13 minutes
Ten questions on text handling and reading and writing files. Tip: remember that string methods return new strings instead of changing the original.
Tap an option to mark your answer. You can change your mind, or tap the same option again to leave the question blank. The correct answers and explanations appear when you finish the test.Tap an option to answer; tap it again to leave the question blank.
Your result
- 0 correct
- 0 wrong
- 0 blank
-
Question 1
s = "Python"
print(s[1:4])What does the code print?
Correct answer: C
Slicing starts at index 1 (y) and stops before index 4, giving y, t and h.
-
Question 2
print("a,b,c".split(","))
What does the code print?
Correct answer: A
split returns a list of the pieces between the separators.
-
Question 3
name = "Ana"
age = 30
print(f"{name} is {age}")What does the code print?
Correct answer: B
An f-string replaces each expression in braces with its value.
-
Question 4
s = "cat"
s[0] = "b"What happens when this code runs?
Correct answer: D
Strings are immutable. To get "bat" you would build a new string, for example "b" + s[1:].
-
Question 5
print("-".join(["x", "y", "z"]))
What does the code print?
Correct answer: A
join puts the separator between the items only, not before the first or after the last.
-
Question 6
print("banana".replace("a", "o", 2))
What does the code print?
Correct answer: C
The third argument limits replacement to the first two occurrences of a.
-
Question 7
Which mode should you pass to open() to add new text to the end of an existing file without erasing what is already in it?
Correct answer: B
Append mode writes at the end. "w" truncates the file first, "r" only reads and "x" fails if the file already exists.
-
Question 8
Why do many programmers write file code inside a with open(...) as f: block?
Correct answer: D
The with statement guarantees clean-up. It does not change speed or locking behavior.
-
Question 9
print("hello".find("z"))
What does the code print?
Correct answer: C
find returns -1 when the text is not found. The similar index method raises a ValueError instead.
-
Question 10
with open("data.txt") as f:
lines = f.readlines()
print(repr(lines[0]))The file data.txt contains two lines, red and blue. What does the code print?
Correct answer: A
readlines keeps the newline character at the end of each line, and repr makes it visible.
Questions you leave blank are not counted as wrong.