Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
path.split('/') solution in Clear category for Simplify Unix Path by martin.pilka
def simplify_path(path):
# Handle empty input
if not path:
return ''
# Set absolute flag
is_absolute = path[0] == '/'
dirs = []
for d in path.split('/'):
if d in ['', '.']:
# Ignore '' (multiple '/' chars, e.g. '///') and '.' (current dir)
continue
elif d == '..':
# Separate logic for '..'
if dirs and dirs[-1] != '..':
# There is a dir which can be ignored
dirs.pop()
elif not is_absolute:
# No dir to be ignored, store '..' if path is relative (otherwise ignore it)
dirs.append('..')
continue
# Regular dir, just append it to a list
dirs.append(d)
# Handle special case when dirs is empty
if not dirs:
return '/' if is_absolute else '.'
# Return dirs
return ('/' if is_absolute else '') + '/'.join(dirs)
Feb. 15, 2019
Comments: