Reputation: 131
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
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
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
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
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
Reputation: 7432
I think the easiest way is to replace '//'
with '/'
twice:
a = '/home//user////document/test.jpg'
a.replace('//', '/').replace('//', '/')
Upvotes: 0