Dilu Vinayan
Dilu Vinayan

Reputation: 131

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

My path:

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

I want this to be converted into:

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

How to do this?

Upvotes: 9

Views: 1963

Answers (5)

Georgy
Georgy

Reputation: 13697

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

Upvotes: 0

CashewNuts
CashewNuts

Reputation: 1

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 ;)

Upvotes: 0

deceze
deceze

Reputation: 522081

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'

Upvotes: 9

Piyush Sambhi
Piyush Sambhi

Reputation: 883

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'

Upvotes: 5

Djib2011
Djib2011

Reputation: 7432

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

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

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

Upvotes: 0

Related Questions