Normalise a File Path

medium
Unit 16 · Strings IV0/3 to milestone

Turning "/srv//app/./logs/../data/" into "/srv/app/data" is everyday path handling, and getting it wrong causes path-traversal security bugs, where ../../etc/passwd escapes the folder you meant to allow.

Implement normalize(path) for POSIX-style paths:

  • Collapse repeated slashes, drop . segments, and resolve .. by removing the previous segment.
  • For absolute paths (starting with /), .. at the root stays at the root. For relative paths, leading .. segments that can't be resolved are kept.
  • No trailing slash, except the root itself ("/"). An empty relative result is ".".

Then implement is_safe_join(base, user_path): True if joining the relative user_path onto the absolute base and normalising stays inside base. Absolute user_path values are never safe. Don't use os.path or pathlib.

#strings#stacks#security2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Normalise a File Path · TechGradify