Ahmad
Ahmad

Reputation: 9658

How to get path without trailing slash or backslash

I want to have a path like

"/path/to/somthing" or in some OS "\path\to\something" 

as

"path/to/something" or "path\to\something"

I tried:

>>> test = "\ali"
>>> test.strip("/\\")
'\x07li'

But it outputs corrupt output.

It may or may not have trailing slashes and it could be a variable passed to a function without knowing its value.

Upvotes: 1

Views: 1997

Answers (2)

tenhjo
tenhjo

Reputation: 4537

I strongly recommend to use os.path or pathlib when working with paths and directories. For example, os.path.normpath("example/path/") gives you a standard format for you paths, also without the final slash.

Upvotes: 2

Ahmad
Ahmad

Reputation: 9658

The following solution works:

path = path.strip(r'\/')

Upvotes: 0

Related Questions