-1

Suppose I have a filename ./file and I want to remove the leading ./ (if it starts with ./). What would be the best python way to do this? My take at this is:

if filename.startswith("./"):
  # remove leading ./
  filename = filename[2:]

Isn't there a more elegant way?

PS: it should remove the leading part only if it matches exactly, think of the following filenames:

./filename
.configfile
../file
./.configfile
Chris Maes
  • 35,025
  • 12
  • 111
  • 136

6 Answers6

1
filenames = ['.configfile', './file1', './dir/file2']
filenames = [fn[2:] if fn.startswith("./") else fn for fn in filenames]

borrowing from your idea but doing it in one line

user1443098
  • 6,487
  • 5
  • 38
  • 67
1

My personal preference would be the solution by @user1443098 But for completnes - using re

import re

pattern = re.compile(r'^\./')
files = ['./filename', '.configfile', '../file']
new_files = [re.sub(pattern, '', fname) for fname in files]
print(new_files)
buran
  • 13,682
  • 10
  • 36
  • 61
0

The way you do it is the ways it's usually done. Of course, you can always move it into a function:

def remove_prefix(s, prefix):
    if s.startswith(prefix):
        s = s[len(prefix):]
    return s
äymm
  • 411
  • 4
  • 14
0

I would consider writing a helper function:

def strip_prefix(s, prefix):
  if s.startswith(prefix):
    return s[len(prefix):]
  else:
    return s

print(strip_prefix('./filename', './'))
print(strip_prefix('.configfile', './'))
print(strip_prefix('../file', './'))
NPE
  • 486,780
  • 108
  • 951
  • 1,012
-1

Assuming you are using python3, the best way to deal with paths is trough the pathlib module:

if you only want the filename

from pathlib import Path
paths = ["./filename", ".configfile", "../file"]
only_filenames = [Path(f).name for f in paths]
Hrabal
  • 2,403
  • 2
  • 20
  • 30
  • 1
    This is not what the question asks, only exact matches to `./` should be removed, something like `../` should stay the same. Nowhere is stated that only the filename is wanted – FlyingTeller Sep 10 '19 at 13:42
-3
if filename.startswith("./"):
    filename.lstrip("./")