Q.What is the output of the following code snippet ? s='War and Peace by Leo Tolstoy' print(s.partition("by")) (A) ('War and Peace ', 'by', ' Leo Tolstoy') (B) ['War and Peace ', 'by', ' Leo Tolstoy'] (C) ('War and Peace ', ' Leo Tolstoy') (D) ['War and Peace ', ' Leo Tolstoy']
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The partition() method splits a string at the first occurrence of a separator and returns a tuple of three parts: everything before the separator, the separator itself, and everything after. For s.partition("by"), the output is ('War and Peace ', 'by', ' Leo Tolstoy'), which matches option (A).
The key here is understanding what partition() does in Python — and what it returns. Many students confuse it with split() or forget that it returns a tuple, not a list.
partition() is a string method that searches for a given separator in the string. When it finds the first occurrence, it cuts the string into three pieces: the part before the separator, the separator itself, and the part after. If the separator isn't found, it returns the original string followed by two empty strings. The result is always a tuple of three strings.
Let's trace through the code:
-
The string
sis'War and Peace by Leo Tolstoy'. The separator we're looking for is"by". -
Python scans the string from left to right. The first occurrence of
"by"appears after'War and Peace '— note the space before"by"is part of the first segment, not the separator. The separator"by"itself is exactly those two characters. -
Everything before
"by"is'War and Peace '(including the trailing space). The separator itself is'by'. Everything after"by"is' Leo Tolstoy'(starting with a space). -
partition()packages these three strings into a tuple:('War and Peace ', 'by', ' Leo Tolstoy'). …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.