Compact spaces
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Replace every run of whitespace with one ASCII space and remove leading/trailing whitespace.
Examples
' hello world ''hello world''\ta\nb''a b'''''What this exercise practices
Normalize word separators in a display string while preserving the words themselves. This is useful for labels and search text when all whitespace should have the same meaning.
Common mistakes and boundary checks
- Check tabs, newlines, leading whitespace, and a string containing only whitespace.
- Do not remove every space: word boundaries must remain.
- Use the stated Python whitespace rules; splitting only on a literal space treats tabs differently.
Constraints
0–10,000 characters. Use Python str.split whitespace semantics.
Review lesson: Methods and normalizationA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- Split without an explicit separator.
- Join the words with one space.
Worked solution
Try your own approach first, then compare the reasoning.
def compact_spaces(s):
return " ".join(s.split())
split() discards surrounding whitespace and groups adjacent whitespace. Joining reconstructs exactly one separator per word boundary.
Complexity
O(n) time and O(n) space.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.