Reverse Words in String

easyPython

Lesson

String Manipulation and Preserving Structure

When working with strings, we often need to modify content while preserving the original structure or formatting. This is a common challenge in text processing where you want to change the data but maintain visual consistency.

The Challenge of Structure Preservation

Consider a simple approach to reversing words: split the string into words, reverse them, and join them back. This works for basic cases, but what about strings like "hello world" with multiple spaces? A naive approach might turn this into "world hello", losing the original spacing.

The key insight is to separate content from structure. We need to:

  1. Identify what needs to change (the words)
  2. Identify what needs to stay the same (the spacing pattern)
  3. Apply changes to content while preserving structure

Strategic String Splitting

Python's split() method has different behaviors depending on how you call it:

  • s.split() splits on any whitespace and removes empty strings
  • s.split(' ') splits only on single spaces and keeps empty strings

The second approach is crucial for preserving spacing information. When you split "a b" with split(' '), you get ['a', '', '', 'b']. Those empty strings represent the extra spaces!

Reconstruction Strategy

Once you have the split result, you can:

  1. Extract the actual words (non-empty parts)
  2. Modify them as needed (reverse, transform, etc.)
  3. Walk through the original split result and substitute modified words while preserving empty strings (spaces)
Example
1text = "apple banana cherry" 2parts = text.split(' ') # ['apple', '', '', '', 'banana', '', '', '', 'cherry'] 3 4# Extract actual words 5words = [part for part in parts if part] # ['apple', 'banana', 'cherry'] 6 7# Transform the words (uppercase them) 8transformed = [word.upper() for word in words] 9 10# Reconstruct with original spacing 11result = [] 12word_index = 0 13for part in parts: 14 if part: # This was a word position 15 result.append(transformed[word_index]) 16 word_index += 1 17 else: # This was a space position 18 result.append('') 19 20final = ' '.join(result) # "APPLE BANANA CHERRY"
L2split(' ') preserves spacing as empty strings in the list
L5Extract only non-empty parts to get the actual content
L12Substitute transformed words while preserving empty string positions

Key Takeaways

  • •Use split(' ') instead of split() when you need to preserve spacing information
  • •Separate content transformation from structure preservation by working with two lists
  • •Empty strings in split results represent the spaces you need to maintain
Loading...