PCEP-30-02 · Question #121
What is the expected output of the following code? ``python x = '\\' print(len(x)) ``
The correct answer is B. 1. Option B is correct because '\\' is a Python string containing exactly one character - a literal backslash. The \\ is an escape sequence: the first \ signals "escape the next character," and the second \ is the character being escaped, resulting in a single \ stored in memory…
Question
x = '\\'
print(len(x))
Options
- A0
- B1
- CThe code is erroneous.
- D2
How the community answered
(25 responses)- A16% (4)
- B76% (19)
- C4% (1)
- D4% (1)
Explanation
Option B is correct because '\\' is a Python string containing exactly one character - a literal backslash. The \\ is an escape sequence: the first \ signals "escape the next character," and the second \ is the character being escaped, resulting in a single \ stored in memory. So len(x) evaluates to 1.
Why the distractors are wrong:
- A (0): The string is not empty - it holds one character. An empty string
''would givelen()of 0. - C (erroneous): The syntax is perfectly valid Python;
\\is a well-defined escape sequence. - D (2): The most common trap - it counts the source characters (
\and\) rather than the runtime value. Escape sequences are resolved when the string is created, so only one character exists at runtime.
Memory tip: Think of escape sequences as collapsing pairs - \\ is two characters in your code, but Python "collapses" them into one actual character. When in doubt, mentally count the backslashes after escaping, not before.
Community Discussion
No community discussion yet for this question.