A developer is writing a function to reverse each word in a sentence while preserving the original order of the words. For example, 'Hello World' should become 'olleH dlroW'. The current implementation is: def reverse_words(s): return ' '.join(word[::-1] for word in s.split()). This works for simple cases. However, the input may contain multiple spaces between words (e.g., 'Hello World') and tabs. The requirement is to preserve the exact whitespace between words (including tabs and multiple spaces) in the output. Which of the following modifications will achieve this while keeping the approach efficient?
Splitting on whitespace collapses runs of spaces and tabs, losing the original separators. Capturing the whitespace with re.split(r'(\s+)') keeps those groups in the list, so reversing only the word elements and rejoining preserves exact spacing.
Why this answer
`re.split(r'(\s+)', s)` splits the string into a list where every other element is a whitespace segment (preserving exact spaces and tabs), and the word segments can be reversed individually. Joining the list back with `''.join(...)` reconstructs the original whitespace exactly, meeting the requirement efficiently without manual iteration.
Exam trap
The Python Institute often tests the distinction between `str.split()` (which collapses all whitespace) and `re.split` with a capturing group (which preserves whitespace), and the trap here is assuming that simple `split` and `join` can handle arbitrary whitespace patterns without losing information.
How to eliminate wrong answers
Option A is wrong because `s.split(' ')` splits only on single spaces, not tabs, and handling empty strings does not preserve multiple spaces or tabs correctly. Option B is wrong because manually iterating and detecting word boundaries is inefficient and error-prone, and the PCAP exam expects use of built-in or regex solutions. Option D is wrong because `s.split()` collapses all whitespace (including tabs and multiple spaces) into single spaces, losing the original whitespace pattern, and a separate loop to track whitespace would be complex and not preserve tabs.