How to replace multiple forward slashes in a directory by a single slash?

Viewed 544

My path:

'/home//user////document/test.jpg'

I want this to be converted into:

'/home/user/document/test.jpg'

How to do this?

5 Answers

Use os.path.abspath or normpath to canonicalise the path:

>>> import os.path
>>> os.path.abspath('/home//user////document/test.jpg')
'/home/user/document/test.jpg'

Solution:
This code snippet should solve your issue:

import re
x = '/home//user////document/test.jpg'
re.sub('/+','/', x)

Output:

'/home/user/document/test.jpg'

this solution is very simple by using Regex.
You can use it 're' module of the Python standard library.

import re

old_path = '/home//user////document/test.jpg'
converted_path = re.sub('/+', '/', old_path)

I'm sorry not to speak English fluently ;)

Instantiating a pathlib.Path object from your string will remove redundant slashes automatically for you:

from pathlib import Path

path = Path('/home//user////document/test.jpg')
print(path)
# /home/user/document/test.jpg

I think the easiest way is to replace '//' with '/' twice:

a = '/home//user////document/test.jpg'

a.replace('//', '/').replace('//', '/')
Related